1

need some help with some associations in my rails app. Get a "can't mass-assign protected attributes: rss_readers" warning and don't figured out what's the problem.

class Scraper < ActiveRecord::Base
  attr_accessible :name, :link, :rss_reader_attributes

  has_one :rss_reader
  accepts_nested_attributes_for :rss_reader

And the accociation:

class RssReader < ActiveRecord::Base
  attr_accessible :title, :address, :content 

  belongs_to :scraper

At the rails console its works fine.

> scraper = Scraper.new 
> scraper.build_rss_reader 
> scraper.attributes={:rss_reader_attributes=>{:address => "asdsad"}}

But in controller i get the warning.

  def new
    @scraper = Scraper.new
    @scraper.build_rss_reader
  end

  def create
    @scraper = Scraper.new(params[:scraper])
    @scraper.build_rss_reader

    if @scraper.save
      redirect_to :show
    else
      render :new
    end

And thats the new view

<%= form_for(@scraper) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <%= f.fields_for(@scraper.rss_reader) do |rss| %>
     <div class="field">
         <%= rss.label :address %><br />
         <%= rss.text_field :address %>
     </div>
  <% end %>
  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
<% end %>

I thougth that's all right but i get the warning. Anyone have an idea?

Thanks

mibo
  • 73
  • 1
  • 8

2 Answers2

2

Based on this you may need to explicitly add RssReader to :attr_accessible.

ScottJShea
  • 7,041
  • 11
  • 44
  • 67
  • 1
    this didn't work. i add :rss_reader to :attr_accessible. get this error. RssReader(#70085183525060) expected, got ActiveSupport::HashWithIndifferentAccess(#9179800) – mibo Feb 16 '12 at 11:05
2

Basically when you say something to be attribute accessible, then you cannot mass assign that particular attribute ... so the error you are getting is right. You cannot do object.update_attributes

what you can try is do 
@rssreader = rssreader.new
@rssreader.address = 'the address'
and then 
@scrapper.rssreader = @rssreader

Refer this for a better idea on attr_accessible Rails mass assignment definition and attr_accessible use

Community
  • 1
  • 1
Ross
  • 1,562
  • 1
  • 15
  • 26
  • thanks for response. so I thought I would have understood the mass assignment technique, so thats why I added rss_reader_attributes to the parent model. because I would like to create a scraper object and a child, nested object RSS reader in a form. i think there must be a way to create a scraper with rss_reader accociation and write the nested attributes. by the way my english is not so good, I hope I express myself to understand. – mibo Feb 16 '12 at 19:32
  • yeah get it. my mistake wasn't in the controller or the model. I've to used the :rss_reader symbol instead of @scraper.rss_reader in the field field_for at my new view. but i don't understood exactly why or where is it create? – mibo Feb 16 '12 at 19:44