[英]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.