【问题标题】:Rails, nested attributes, can't mass assign errorRails,嵌套属性,不能批量分配错误
【发布时间】:2012-11-27 13:24:34
【问题描述】:

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

饲料

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

在我的客户端上,我有用于广播和提要的基本 ActiveResource 类

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

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

【问题讨论】:

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


    【解决方案1】:

    我认为您需要在广播模型中添加一个名为 feed_id 的列,而 attr_accessible 将是

    attr-accessible :feed_id
    

    在广播模型中

    需要创建外键

    【讨论】:

      【解决方案2】:

      您不能直接将提要分配给 feed_attributes 散列(如果这是您实际尝试做的)。

      broadcast.feed_attributes &lt;&lt; feed(不应该是feed1吗?)更改为:

      broadcast.feed_attributes << feed1.attributes
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多