2

我有一个由用户创建的名为 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。但是您只能从用户转到挑战。对用户的挑战返回 Nil。

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
4

2 回答 2

3

根据:http ://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html外键应该是:

:foreign_key => :author_id

不要忘记添加字段。祝你好运!

于 2012-05-14T02:13:11.270 回答
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
于 2012-05-14T01:33:04.320 回答