我有一个名为Challenge的模型,由用户创建。它也有与之相关的难度。当我创建挑战并将其交给作者(用户)和难度时,难度助手会起作用,但作者(用户)不会。最奇怪的部分是,当您查看Challenge对象时,它会显示与之关联的Author键。
challenge = Challenge.first
challenge.author (prints Nil) #Doesn't even run a Query
当我使用以下代码创建挑战时,user_id为Nil。
user = User.find(1)
diff = Difficulty.find(1)
Challenge.create(:author => user, :difficulty => diff, :title => "My Challenge")
当我使用此代码创建挑战时,用户获得与挑战的关系,挑战获得用户的user_id。但是你只能从用户到挑战。对用户的挑战回报无。
user = User.find(1)
diff = Difficulty.find(1)
chall = Challenge.create(:difficulty => diff, :title => "My Challenge")
user.authored_challenges << chall
以下是我的模型和表格
# Models
class User < ActiveRecord::Base
has_many :authored_challenges, :class_name => "Challenge"
attr_accessible :display_name, :authored_challenges
end
class Reward < ActiveRecord::Base
has_many :challenges
attr_accessible :name, :value, :challenges
end
class Challenge < ActiveRecord::Base
belongs_to :reward
belongs_to :author, :class_name => "User"
attr_accessible :title, :description, :reward, :author
end
# Tables
create_table :users do |t|
t.string :display_name
t.timestamps
end
create_table :rewards do |t|
t.string :name
t.float :value
t.timestamps
end
create_table :challenges do |t|
t.integer :user_id
t.integer :reward_id
t.string :title
t.string :description
t.timestamps
end
答案 0 :(得分:3)
根据:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html,外键应该是:
:foreign_key => :author_id
不要忘记添加字段。祝你好运!
答案 1 :(得分:1)
你试过了吗?
belongs_to :author, :class_name => "User", :foreign_key => :user_id
来自Rails文档:
按照惯例,Rails假定用于在此模型上保存外键的列是添加了后缀_id的关联的名称。 :foreign_key选项允许您直接设置外键的名称
文档中给出的示例与您拥有的示例非常相似:
class Order < ActiveRecord::Base
belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
end