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.

3
  • One minor thought. From the Rails docs on "belongs_to": By default this [foreign_key] is guessed to be the name of the association with an “_id” suffix. So the two :foreign_key options on your model are redundant.
    – GSP
    Oct 5, 2012 at 13:55
  • 2
    Yes, what's up with the 14%?
    – Abram
    Dec 24, 2012 at 1:26
  • I don't know what's up with the 14%. Probably it's a combination of laziness and being an eclectic jerk who's moved on to Java by the time someone sees my Rails question (for example). But on the other hand, are you saying you've looked through all my questions and you know that the percentage with good answers is significantly higher than that? Nov 14, 2013 at 15:33

1 Answer 1

54

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.

1
  • Saved me a big headache, thanks! Forgot to test:prepare after I changed schema. Jan 28, 2013 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.