Rahul
2011-Oct-11 02:32 UTC
Is this functionality achievable through accepts_nested_attributes_for
I have these four models class Comment < ActiveRecord::Base has_many :relationships has_many :advantages, :through => :relationships, :source => :resource, :source_type => ''Advantage'' has_many :disadvantages, :through => :relationships, :source => :resource, :source_type => ''Disadvantage'' accepts_nested_attributes_for :advantages, :disadvantages end class Advantage < ActiveRecord::Base has_many :relationships, :as => :resource has_many :comments, :through => :relationships end class Disadvantage < ActiveRecord::Base has_many :relationships, :as => :resource has_many :comments, :through => :relationships end class Relationship < ActiveRecord::Base belongs_to :resource, :polymorphic => true belongs_to :comment end Since I have related commennts with advantages, disadvantages and have given the attribute `accepts_nested_attributes_for`, when I try to save new record of comments with new records of advantages, it saves. For example params = { :comment => { :comment => ''This is a sample comment'', :advantages_attributes => [ { :plus => ''This is a good product'' }, { :plus => ''It has all the functionality'' }, { :plus => ''Performs bette than others''} ] } } comment = Comment.create(params[:comment]) This saves 3 records of advantages and 1 comment to the database and makes 3 entries in the relationship table. But not always I want to create new entries for the advantages, if there are already existing advantages, I would like to send just the id, so only the relatioship table is being updated. So my params would be like this params = { :comment => { :comment => ''This is a sample comment'', :advantages_attributes => [ { :id => 1 }, { :plus => ''It has all the functionality'' }, { :plus => ''Performs bette than others''} ] } } Here I want a new comment to be created which has to be associated with the already existing advantage with `id => 1` and create new advantages for the next two and relate it with the comment, but when i try this directly it throws an error. How can I achieve this? -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.