2010-09-06 181 views
1

我爲模型類別和產品(均使用腳手架創建)創建了一個連接表。該產品型號是這樣的:belongs_to has_many協助幫助

class Product < ActiveRecord::Base 
    belongs_to :category 

    def category_id 
    category.id if category 
    end 

    def category_id=(id) 
    self.category = Category.find_by_id(id) unless id.blank? 
    end 
end 

和類型模型是這樣的:

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :products 
end 

在我創建的所有類保管箱供用戶選擇form.html.erb:

<p> 
     <label for="product_category_id">Category:</label><br /> 
     <%= f.collection_select :category_id, Category.find(:all), :id, :name, :prompt => "Select a Category" %> 
</p> 

然而,當我一起來看看產品的展示:

<p> 
    <b>Category:</b> 
    <%= @product.category_id %> 
</p> 

或產品(index.html.erb)的列表:

<td><%= product.category_id %></td> 

有沒有類別。只是空白。我不明白。 category_id方法或關聯有問題嗎?

回答

1

首先,您不需要明確的category_idcategory_id=方法。 ActiveRecord將爲您處理這些關於belongs_to關聯的問題。

其次,您是否想要has_and_belongs_to_manyhas_many/belongs_to關聯之間似乎不匹配。如果你有一個連接表,那麼你有前者,在這種情況下,該協會的雙方應聲明has_and_belongs_to_many。如果您只是在產品表上使用category_id,則類別關聯的另一端應爲has_many :products

隨着加盟模式:

class Categorization < ActiveRecord::Base 
    belongs_to :category 
    belongs_to :product 
end 

你定義在你Product類:

has_many :categorizations 
has_many :categories, :through => :categorizations 

然後,因爲你的公會是一個「多」的關聯,你沒有得到一個.category方法在產品上。但是,您可以獲得categories方法(以及其他幾種方法 - 查看has_many文檔)。如果你的名字是collection_selectcategory_ids那麼它應該按預期工作。您可能還需要將「多個」選項添加到選擇中以選擇多個類別。

+0

我嘗試使用帶有product_id,category_id屬性的連接模型(分類模型)。分類屬於類別和產品。並通過產品使用=>分類。我刪除了category_id方法,但是當我刪除category_id(或兩者)和「undefined local variable或method'category'for#「 :0x10415bfa8>「我刪除category_id =後。什麼似乎是問題?預先感謝您的回覆和您的時間。 – storedope 2010-09-06 18:17:23

+0

我已經更新了我的答案,以包含使用連接表的詳細信息。您的評論的主要問題是,當您想要的關聯適用於多個類別時,您正在嘗試引用單個類別。 – Shadwell 2010-09-06 20:24:04

0

你的關聯顯然是不正確的。正如所指出的那樣,has_many類產品。如果你想使用多對多關係,強烈建議使用has_many:through關係。