16

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.

4

1 回答 1

53

我的经验是,如果您忘记运行rake db:migrate并且rake db:test:prepare在更改架构后会收到此警告。

于 2012-10-09T12:45:47.183 回答