2012-10-21 88 views
1

我有一個用戶模式:的Rails協會(belongs_to的)困境

class User < ActiveRecord::Base 

    has_many :cards 

end 

和顯卡型號:

class Card< ActiveRecord::Base 

     belongs_to :user, :foreign_key => "owner_id" 

    end 

顯卡型號也被稱爲 「owner_id」 的屬性,這是我想喜歡用這樣的方式: Card.first.owner將檢索擁有該卡的用戶

我的問題,因爲我知道,軌道將自動連接ID的但這並不會發生。

在CardController

,軌道卡在創建操作就行了

@card=current_user.cards.new(params[:card]) 

,並說unknown attribute: user_id

我做db:migrate,它仍然是行不通的。

我必須按照以下步驟操作嗎?

@card = Card.new(params[:card]) 
@card.owner_id=current_user.id 

還是我錯過了什麼?

+0

不知道是這樣的話,但你必須在一個錯字字外國 – khustochka

+0

哎呀,它在代碼本身正確拼寫 –

+0

有一個owner_id列,我想要使用 –

回答

1

首先,你不需要這個owner_id列。所有你需要的是

class User 
    has_many :cards 
end 

這會給你@ user.cards

class Card 
    belongs_to :owner, :class_name => "User", :foreign_key => "user_id" 
end 

這會給你@ card.owner

+0

如果我在卡創建後執行@ card.owner,我會得到零。我應該在遷移中還是在控制器中做特別的事情? –