I have the same exact schema as described here with a polymorphic join table: 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
I want to be able to create and update multiple types of polymorphic associations at once, instead of having to do @note.locations << Location.first
or @note.checkpoints << Checkpoint.first
.
Something like @note.create note_joins_params
and @note.update note_joins_params
would be awesome.
The way I've been able to achieve the creation part so far is by passing an array of attributes to @note.note_joins.create
, e.g. :
note_joins_params = [{"notable_id"=>"9225", "notable_type"=>"Location"}, {"notable_id"=>"9220", "notable_type"=>"Checkpoint"}]
@note.note_joins.create note_joins_params
Is there a more Rails-esque way to accomplish this, or proper attributes hash syntax similar to accepts_nested_attributes or something similar?
Also the only way I know of how to do an update
is to first delete all the existing records in the join table and then re-create them, i.e.
@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
For what you want to accomplish, Rails doesn't really have this 'smart_way' of accepting nested attributes if you don't specify the
source_type
. Refer to this The other side of polymorphic :through associationsBut you can try this:
Then in your form, build something like this: