简体   繁体   中英

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 method created_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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM