Rails,嵌套属性,无法批量分配错误

时间:2012-11-27 13:24:34

标签: ruby-on-rails ruby nested activeresource mass-assignment

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

饲料

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

广播

 class Broadcast < ActiveRecord::Base

    validates_presence_of :content

    attr_accessible :content, feeds, feeds_attributes

    belongs_to :user
    has_many :feeds
    accepts_nested_attributes_for :feeds

    def to_s
      result = "id: " + id.to_s + " content: " + content
      if user
        result += " user: " + user.id.to_s
      end
      result
    end

    def self.per_page
      8
    end
    end

在我的客户端上,我有广播和Feed的基本ActiveResource类

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

feed1 = Feed.find(3) <-succesful

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

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

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

会出现以下错误:

无法批量指定受保护的属性:Feed

2 个答案:

答案 0 :(得分:0)

我认为您需要在广播模型中添加名为feed_id的列,并且attr_accessible将

attr-accessible :feed_id
广播模型中的

需要创建外键

答案 1 :(得分:0)

您无法直接将Feed添加到feed_attributes哈希(如果这是您实际尝试的内容)。

broadcast.feed_attributes << feed(不应该是feed1?)更改为:

broadcast.feed_attributes << feed1.attributes