Tôi có schema chính xác giống như mô tả ở đây với một bảng tham gia đa hình: http://aaronvb.com/articles/a-polymorphic-join-table.htmlTạo nhiều bản ghi đa hình cùng một lúc ray
class Location < ActiveRecord::Base
has_many :note_joins, as: :notable
has_many :notes, through: :note_joins
end
class Checkpoint < ActiveRecord::Base
has_many :note_joins, as: :notable
has_many :notes, through: :note_joins
end
class NoteJoin < ActiveRecord::Base
belongs_to :notable, polymorphic: true
belongs_to :note
end
class Note < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :notable, polymorphic: true
belongs_to :user
has_many :note_joins
end
Tôi muốn để có thể tạo và cập nhật nhiều loại hiệp hội đa hình cùng một lúc, thay vì phải làm @note.locations << Location.first
hoặc @note.checkpoints << Checkpoint.first
.
Thứ gì đó như @note.create note_joins_params
và @note.update note_joins_params
sẽ thật tuyệt vời.
Cách tôi đã có thể đạt được phần sáng tạo cho đến nay là bằng cách chuyển một loạt các thuộc tính đến @note.note_joins.create
, ví dụ: :
note_joins_params = [{"notable_id"=>"9225", "notable_type"=>"Location"}, {"notable_id"=>"9220", "notable_type"=>"Checkpoint"}]
@note.note_joins.create note_joins_params
Có cách nào khác để thực hiện điều này hoặc cú pháp băm thuộc tính thích hợp tương tự như accept_nested_attributes hoặc tương tự?
Cũng cách duy nhất tôi biết làm thế nào để làm một update
là trước hết phải xóa tất cả các bản ghi hiện có trong bảng tham gia và sau đó tái tạo chúng, tức là
@note.note_joins.destroy_all
new_note_joins_params = [{"notable_id"=>"9225", "notable_type"=>"Location"}, {"notable_id"=>"9220", "notable_type"=>"Checkpoint"}]
@note.note_joins.create new_note_joins_params
Rails không có hỗ trợ cho accept_nested_attribute cho hiệp hội đa hình. Có lẽ bạn nên kiểm tra chủ đề này http://stackoverflow.com/q/3969025/4587148 – Sajan