我有一个由用户创建的名为 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