简体   繁体   中英

Form control-group for rails polymorphic association

In my rails app I have following models:

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?

Ideally I would use grouped_collection_select and pull first Student and Library and below their ids.

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?

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 .

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 . 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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