Catfish
Catfish

Reputation: 19284

Rails model foreign key not working when specifying explicitly

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

Upvotes: 2

Views: 1859

Answers (1)

Dan McClain
Dan McClain

Reputation: 11920

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"

Upvotes: 2

Related Questions