2012-05-14 26 views
2

我有一個由用戶創建的稱爲挑戰的模型。它也有一個難度。當我創建挑戰並將其作爲作者(用戶)和難度時,難度關聯作品,但作者(用戶)則不具備。最奇怪的部分是,當您查看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 
+0

我應該加上。如果我將模型名稱從作者更改爲用戶。它工作得很好。所以重命名是問題。 Rails 3.1中必須改變的東西 – Spidy

回答

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 
+0

我已經試過了。沒有運氣 – Spidy

+1

我應該注意到,這確實也有效。我必須將foreign_key添加到belongs_to和has_many – Spidy

+0

因此,將foreign_key添加到雙方是關鍵。涼。 –