我有一個由用戶創建的稱爲挑戰的模型。它也有一個難度。當我創建挑戰並將其作爲作者(用戶)和難度時,難度關聯作品,但作者(用戶)則不具備。最奇怪的部分是,當您查看Challenge對象時,它顯示與其關聯的Author鍵。即使存在外鍵,Rails模型也不能訪問belongs_to模型
challenge = Challenge.first
challenge.author (prints Nil) #Doesn't even run a Query
當我創建使用以下代碼是一個挑戰,所述user_id是無。
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
我應該加上。如果我將模型名稱從作者更改爲用戶。它工作得很好。所以重命名是問題。 Rails 3.1中必須改變的東西 – Spidy