簡體   English   中英

Rails多態關聯的表單控制組

[英]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_selectgrouped_collection_select (根據您的要求)來顯示StudentsLibraries來存儲值bookable_id

對於bookable_type ,Rails bookable_type讀取實例的類名稱並捕獲該類名稱,並將其存儲為bookable_type的值。 例如,考慮以下方法

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

上面的代碼段將在books表中創建一個記錄,其中bookable_id = 1bookable_type = "Student"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM