On my server, I have two models:
Broadcast
class Broadcast < ActiveRecord::Base
validates_presence_of :content
belongs_to :user
has_and_belongs_to_many :feeds
attr_accessible :content, :feeds, :feeds_attributes
end
Feed
class Feed < ActiveRecord::Base
has_and_belongs_to_many :broadcasts
attr_accessible :name
end
On my client, I have basic ActiveResource classes for those models.
When I try to create new Broadcast with given Feeds (from client):
feed = Feed.find(3) <-succesful
broadcast = Broadcast.new
broadcast.attributes['feed'] ||= []
broadcast.feed << feed
broadcast.save
In BroadcastController on the server, I simply do
@broadcast = Broadcast.new(params[:broadcast])
it gives following error:
ActiveRecord::AssociationTypeMismatch (Feed(#45931224) expected, got ActiveSupport::HashWithIndifferentAccess(#25685616)):
I tried changing
broadcast.attributes['feed'] ||= []
to
broadcast.attributes['feed_attributes'] ||= []
But it gave me “Unknown attribute error”
nevermind, I was missing:
accepts_nested_attributes_for :feeds
in my Broadcast method.
Anyway, should anyone encounter this question, please note that:
broadcast.attributes['feed_attributes'] ||= []
is correct, without '_attributes' suffix the HashWithIndifferentAccess error still occurs.