我有完全相同的模式与多态连接表说明如下:http://aaronvb.com/articles/a-polymorphic-join-table.html一次创建多个多态性记录轨道
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
我希望能够创建和更新多种类型的多态关联的同时,而不必做@note.locations << Location.first
或@note.checkpoints << Checkpoint.first
。
类似@note.create note_joins_params
和@note.update note_joins_params
会很棒。
到目前为止,我已经能够实现创建部分的方式是将一组属性传递给@note.note_joins.create
,例如, :
note_joins_params = [{"notable_id"=>"9225", "notable_type"=>"Location"}, {"notable_id"=>"9220", "notable_type"=>"Checkpoint"}]
@note.note_joins.create note_joins_params
是否有更多的Rails式的方式来做到这一点,或适当的属性哈希语法类似于accepts_nested_attributes或类似的东西?
也只有这样,我知道怎么做的update
是先删除所有的连接表,然后重新创建这些现有的记录,即
@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的不具备accept_nested_attribute多态协会的大力支持。也许你应该检查这个线程http://stackoverflow.com/q/3969025/4587148 – Sajan