[英]Form control-group for rails polymorphic association
在我的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
在form.html.erb中创建新的书本对象时,如何将t.integer:bookable_id和t.string:bookable_type映射到特定对象?
理想情况下,我将使用grouped_collection_select并将第一个Student和Library拉到其ID之下。
提前致谢。
在form.html.erb中创建新的书本对象时,如何将t.integer:bookable_id和t.string:bookable_type映射到特定对象?
那么,你可以使用collection_select
或grouped_collection_select
(根据您的要求)来显示Students
和Libraries
来存储值bookable_id
。
对于bookable_type
,Rails bookable_type
读取实例的类名称并捕获该类名称,并将其存储为bookable_type
的值。 例如,考虑以下方法
@student = Student.find(1)
@student.books.create
上面的代码段将在books
表中创建一个记录,其中bookable_id = 1
且bookable_type = "Student"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.