[英]Rails: ActiveRecord association won't work when specifying foreign key
[英]Rails model foreign key not working when specifying explicitly
我有一個User
模型和一個Message
模型。 我的message
表具有created_for
和created_by
列,它們都是User
表的外鍵。
我目前收到此錯誤消息:
#的undefined method
created_for_id'
如何在不將列更改為created_for_id
和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
您可以通過以下方式為belongs_to指定外鍵:
belongs_to :created_for, class_name: 'User', foreign_key: :created_for
我懷疑您會遇到一個問題,即關系名稱和外鍵屬性共享一個名稱。 這是belongs_to文檔,向下滾動到“選項”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.