2011-07-29 30 views
0

我需要一些幫助來了解這種關聯類型。看起來沒有多大意義的公會

我有2種型號(ITEM_TYPE和項目)

ITEM_TYPE它只是表現得像一個類別,只有一個字段(標題)

表結構:

ITEM_TYPE:

  • ID
  • 標題
  • created_at
  • 的updated_at

項目:

  • ID
  • item_type_id
  • 標題
  • 價格
  • 其他不相關的領域..

所以,基本上我試圖在這些模型之間做一個簡單的關聯。

class ItemType < ActiveRecord::Base 
    belongs_to :item 
end 

class Item < ActiveRecord::Base 
    has_one :item_type 
end 

我已經創建了一個項目,保存它,但是當我取它表明,它應顯示item_type.title,而不是僅僅item_type.id,對不對?

我饒有興趣的是belongs_to總是在擁有foreign_key的桌子上,但在這種情況下,它對我來說沒什麼意義......甚至可以顛倒關係,將has_one放在ItemType類上以及對Item類的belongs_to,或者這種方式起作用。

在控制器代碼我有:

def show 
    @item = Item.find(params[:id], :include => 'item_type') 
end 

和視圖,應該是可見看到的只是與

<%= debug @item %> 

我做錯了創建的關係?

+0

您是否將正確的ID傳遞給show方法?例如。 'http:// localhost/item/show/24'或'show?id = 24'?您是否在創建Item時爲Item指定了ItemType,例如a = Item.new(:title =>「item title」,:price => 42,:type => ItemType.new(:title =>「item type」)); a.save!'? – Dr1Ku

+0

是的,我剛剛編輯過,你能看到編輯註釋嗎? –

+1

哦忘記它..我刪除了包含參數,它工作正常。只需在視圖上使用@ item.item_type.title來顯示它。謝謝! –

回答

0

我記得你需要把belongs_to的在誰包含外鍵的模式,在您的示例:

class ItemType < ActiveRecord::Base 
    has_one :item 
end 

class Item < ActiveRecord::Base 
    belongs_to :item_type 
end 

documentation

+0

yup!我知道這一點..我只是錯過了在視圖方面顯示所需數據的正確方法。我會考慮這個答案是正確的。謝謝。 –

相關問題