简体   繁体   English

Rails多态关联的表单控制组

[英]Form control-group for rails polymorphic association

In my rails app I have following models: 在我的rails应用程序中,我具有以下模型:

class Book < ApplicationRecord
   belongs_to :bookable, polymorphic: true
end

class Student < ApplicationRecord
   has_many :books, as: :bookable
end

class Library < ApplicationRecord
  has_many :books, as: :bookable
end

When creating a new book object in form.html.erb, how I could map t.integer :bookable_id and t.string :bookable_type to specific object? 在form.html.erb中创建新的书本对象时,如何将t.integer:bookable_id和t.string:bookable_type映射到特定对象?

Ideally I would use grouped_collection_select and pull first Student and Library and below their ids. 理想情况下,我将使用grouped_collection_select并将第一个Student和Library拉到其ID之下。

Thanks in advance. 提前致谢。

When creating a new book object in form.html.erb, how I could map t.integer :bookable_id and t.string :bookable_type to specific object? 在form.html.erb中创建新的书本对象时,如何将t.integer:bookable_id和t.string:bookable_type映射到特定对象?

Well, you can use the collection_select or grouped_collection_select (according to your requirements) to display Students and Libraries to store the values for bookable_id . 那么,你可以使用collection_selectgrouped_collection_select (根据您的要求)来显示StudentsLibraries来存储值bookable_id

For bookable_type , Rails under the hood reads the class names of the instances and captures the class name and stores it as a value for bookable_type . 对于bookable_type ,Rails bookable_type读取实例的类名称并捕获该类名称,并将其存储为bookable_type的值。 For example, consider the below approach 例如,考虑以下方法

@student = Student.find(1)
@student.books.create

The above code snippet will create a record in books table with bookable_id = 1 and bookable_type = "Student" 上面的代码段将在books表中创建一个记录,其中bookable_id = 1bookable_type = "Student"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM