Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing arbitrary attributes on a model is deprecated. (Multiple belongs_to on model)

I have multiple belongs_to relationships to the same model. Modeling messages between two users as follows (in the Message model):

  belongs_to :to, :class_name => 'User', :foreign_key => 'to_id'
  belongs_to :from, :class_name => 'User', :foreign_key => 'from_id'

  attr_accessible :to, :from # ...

The corresponding has_many calls are in the User model. Everything works in the spec and the console as I need it to, with the exception of the following deprecation warning (for both from_id and to_id):

DEPRECATION WARNING: You're trying to create an attribute `from_id'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` 

The relevant spec follows:

  it "can associate users" do
    User.delete(:all)
    ufrom = FactoryGirl.create(:DrKevorkian)
    ufrom.save!
    uto = FactoryGirl.create(:JohnSmith)
    uto.save!

    m = Message.new
    m.from = ufrom   # <-- Warning here
    m.to = uto       # <-- Warning here
    m.save

    m.from.id.should == ufrom.id
    m.to.id.should == uto.id

  end

It seems to me the warning is happening as a result of the belongs_to association -- is there a cleaner/better way to do this?

Thanks very much.

like image 298
John Lockwood Avatar asked Sep 12 '12 19:09

John Lockwood


1 Answers

My experience is that you get this warning if you forgot to run rake db:migrate and rake db:test:prepare after changing your schema.

like image 186
Chris Peters Avatar answered Oct 19 '22 02:10

Chris Peters