2010-09-05 55 views
0

我爲此目的創建了一個連接表。下面的代碼:產品 - 分類關聯。 (編輯)belongs_to,has_and_belongs_to_many?

class CreateCategoriesProductsJoin < ActiveRecord::Migration 
    def self.up 
    create_table 'categories_products', :id => false do |t| 
     t.column 'category_id', :integer 
     t.column 'product_id', :integer 
    end 
    end 

    def self.down 
    drop_table 'categories_products' 
    end 
end 

產品型號:

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
    attr_accessor :new_category_name 
    before_save :create_category_from_name 

    def create_category_from_name 
    create_category(:name => new_category_name) unless new_category_name.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" %> 
     or create one: 
     <%= f.text_field :new_category_name %> 
</p> 

我嘗試加載類別的選擇框,但我得到一個消息「未定義的方法`CATEGORY_ID」爲#」。

我不明白爲什麼?我也嘗試過has_many:通過但發生了同樣的事情。

我應該能夠以這種方式繪製類別,因爲它們是關聯的,但我不是。有任何想法嗎?

我試過從railscast.com的screancast,但沒有運氣。你有沒有想到一個完整的教程/產品類別,子類別關聯的例子?我還沒有找到一個下降(除了railscast,但不適合我)。

非常感謝您的時間,並感謝您花時間回覆的麻煩(如果您確實如此)。

編輯:我發現它是在產品模型中的問題。這裏是修復:

class Product < ActiveRecord::Base 
    belongs_to :category 

    def category_name 
    category.name if category 
    end 

    def category_name=(name) 
    self.category = Category.find_by_name(name) unless name.blank? 
    end 

end 

編輯2:我也有類別的另一個問題。

類別名稱未出現在視圖中。我稱之爲category_name函數,但我沒有得到任何回報。像這樣(show.html.erb):

<p> 
     <label for="product_category_id">Category:</label><br /> 
     <%= f.collection_select :category_name, Category.find(:all), :id, :name, :prompt => "Select a Category" %> 
     or create one: 
     <%= f.text_field :new_category_name %> 
</p> 

或(show.html.erb):

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

我試圖改變has_and_belongs_to_many :categories至少我回來了 「分類」 爲這個名字很奇怪......因爲我有4個類別。

A產品只屬於一個類別。 PS:再一次,謝謝你的時間。

回答

0
<%= f.collection_select :category_id ... %> 

即線正在尋找.category_id形式對象,它具有依賴性的形式是爲(我假設它是一個產品對象)創建的對象上訪問器上。產品對象具有has_and_belongs_to_many與類別關係的屬性,但它不是單個類別ID。可用的方法列於here。我不能肯定,因爲我從來沒有使用has_and_belongs_to_many,但我想你會想

<%= f.collection_select :categories_singular_ids ... %> 

的collection_select將需要多選,所以對你的HTML,你會想在:multiple => true最後的選項散列。

+0

不說也不行。 – storedope 2010-09-05 21:52:09

0

嘗試以下操作:

<%= f.select :category_ids, Category.pluck(:name, :id), { prompt: "Select a Category" }, multiple: true %> 

不要忘記允許category_ids,即: params.require(:product).permit(category_ids: [])