Rails,has_and_belongs_to_many,:HashWithIndifferentAccess错误

时间:2012-11-27 14:58:15

标签: ruby-on-rails ruby client-server activeresource has-and-belongs-to-many

在我的服务器上,我有两个型号:

广播

class Broadcast < ActiveRecord::Base

  validates_presence_of :content

  belongs_to :user

  has_and_belongs_to_many :feeds

  attr_accessible :content, :feeds, :feeds_attributes

end

饲料

class Feed < ActiveRecord::Base
  has_and_belongs_to_many :broadcasts
  attr_accessible :name
end

在我的客户端上,我为这些模型提供了基本的ActiveResource类。

当我尝试使用给定的Feeds(来自客户端)创建新的广播时:

feed = Feed.find(3) <-succesful

broadcast = Broadcast.new
broadcast.attributes['feed'] ||= [] 
broadcast.feed << feed
broadcast.save

在服务器上的BroadcastController中,我只是做

@broadcast = Broadcast.new(params[:broadcast])

它出现以下错误:

  

ActiveRecord :: AssociationTypeMismatch(Feed(#45931224)期待,得到   的ActiveSupport :: HashWithIndifferentAccess(#25685616)):

我尝试过更改

broadcast.attributes['feed'] ||= [] 

broadcast.attributes['feed_attributes'] ||= [] 

但它给了我“未知属性错误”

1 个答案:

答案 0 :(得分:0)

没关系,我失踪了:

accepts_nested_attributes_for :feeds

在我的广播方法中。

无论如何,如果有人遇到这个问题,请注意:

broadcast.attributes['feed_attributes'] ||= [] 

是正确的,没有'_attributes'后缀仍然会出现HashWithIndifferentAccess错误。