Search code examples
ruby-on-railsrubynestedactiveresourcemass-assignment

Rails, nested attributes, can't mass assign error


I have two models on server:

Feed

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

Broadcast

 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

On my client, I have basic ActiveResource classes for Broadcast and Feed

When I try to create new Broadcast with given Feeds (from client):

feed1 = Feed.find(3) <-succesful

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

In BroadcastController on the server, I simply do

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

which gives the following error:

Can't mass-assign protected attributes: feed


Solution

  • I think you need to add a column called feed_id to your broadcast model and attr_accessible will be

    attr-accessible :feed_id
    

    within the broadcast model

    need to create a foreign key