2

I have a User model and a Message model. My message table has the columns created_for, and created_by and these are both foreign keys to the User table.

I'm currently getting this error message:

undefined methodcreated_for_id' for #`

How can I get this to work without having to change my columns to created_for_id and created_by_id?

class User < ActiveRecord::Base

    has_one :message
end

class Message < ActiveRecord::Base

    #belongs_to :user
    belongs_to :created_by, :class_name => "User" # Basically tell rails that created_by is a FK to the users table
    belongs_to :created_for, :class_name => "User"  # Basically tell rails that created_for is a FK to the users table

    attr_accessible :created_by, :created_for, :message

end

1 Answer 1

2

You can specify the foreign key for the belongs_to via:

belongs_to :created_for, class_name: 'User', foreign_key: :created_for

I suspect you are going to run into an issue having the relation name and foreign key attribute sharing a name. Here is the belongs_to documentation, scroll down to the "Options"

Sign up to request clarification or add additional context in comments.

5 Comments

I added the foreign_key and i get this error: User(#70281925609240) expected, got String(#70281918088560). The line that throws the error is: @message = Message.new(params[:message]) and here's the params {"utf8"=>"✓", "authenticity_token"=>"EYvFRZkOlK0rB5Dvflfa8iN47rZUorPle3usdaSRobk=", "message"=>{"created_for"=>"1", "message"=>"asdf"}, "button"=>"", "action"=>"create", "controller"=>"messages"}
It has to be because the relation and the foreign key have the same name. I would change the name of one of them, as it's only going to cause problems, maybe call the relation for instead of created_for
So if changed the column names to for and by, what would the foreign_key need to be? I guess i don't understand how changing for and by would make anything different.
If the column was for, your relation would be defined like this belongs_to :created_for, class_name: 'User', foreign_key: 'for' when you had both the relation and the column sharing a name, when you set the foreign key on the model, it was doing a check to make sure it was the type specified in the belongs_to
I just changed belongs_to :for. I used to think that a belongs_to had to be the label of your column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.