2012-05-14 47 views
5

我正在使用rails來創建新產品,並且希望爲每個產品添加一個類別。Rails嵌套屬性 - 如何將類別屬性添加到新產品?

我有三個表:產品,類別和分類(存儲產品和類別之間的關係)。我試圖使用嵌套屬性來管理分類的創建,但不確定應如何更新我的控制器和視圖/窗體,以便新產品也更新分類表。

這裏是我的模型:

class Product < ActiveRecord::Base 
belongs_to :users 
has_many :categorizations 
has_many :categories, :through => :categorizations 
has_attached_file :photo 
accepts_nested_attributes_for :categorizations, allow_destroy: true 

attr_accessible :description, :name, :price, :photo 

validates :user_id, presence: true 

end 


class Category < ActiveRecord::Base 
attr_accessible :description, :name, :parent_id 
acts_as_tree 
has_many :categorizations, dependent: :destroy 
has_many :products, :through => :categorizations 

end 


class Categorization < ActiveRecord::Base 
    belongs_to :category 
    belongs_to :product 
    attr_accessible :category_id, :created_at, :position, :product_id 

end 

這是我的新產品控制器:

def new 
    @product = Product.new 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @product } 
    end 
    end 

這裏是我的看法形式:

<%= form_for @product, :html => { :multipart => true } do |f| %> 
    <% if @product.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2> 

     <ul> 
     <% @product.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :description %><br /> 
    <%= f.text_field :description %> 
    </div> 
    <div class="field"> 
    <%= f.label :price %><br /> 
    <%= f.number_field :price %> 
    </div> 
<div class="field"> 
<%= f.file_field :photo %> 
</div> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

我應該如何更新我的控制器以便在添加新產品時更新產品和分類表?如何更新我的視圖文件,以便類別顯示在下拉菜單中?

+0

*,但不知道該如何我...視圖/表單應該更新* - 我們也不知道,因爲你沒有暴露它們。 – jdoe

+0

Hi @jdoe - 我在這裏添加了視圖文件。只是由rails生成的命令創建的標準。 –

回答

4

我看到該產品has_many類別。很自然地允許用戶在產品創建/版本中指定它們。一種方法描述爲here(通過複選框將類別指定給您的產品)。另一種方法:如通常創建產品,並允許添加/刪除類別的編輯頁面,如:

cat_1 [+] 
cat_2 [-] 
cat_3 [+] 

而且看看Railcasts,像this one做它一個更華麗的方式。

0

,首先展現在視圖文件中使用的一些類別,如下面的顯示類下拉

<%= select_tag("category_id[]", options_for_select(Category.find(:all).collect { |cat| [cat.category_name, cat.id] }, @product.category.collect { |cat| cat.id}))%> 

然後在創建產品控制器的方法,這樣做以下

@product = Product.create(params[:category]) 
@product.category = Category.find(params[:category_id]) if params[:category_id] 

我希望這會幫助你。
謝謝。

0

RailsCasts 嵌套模型表單教程也許幫助你,或者它可能會幫助別人。

0

這裏是我addded我的產品視圖文件,在_form.html - 這創造,我可以用每個產品選擇多個類別多個複選框:

</div class="field"> 
<% Category.all.each do |category| %> 
<%= check_box_tag "product[category_ids][]", category.id %> 
<%= label_tag dom_id(category), category.name %><br> 
<% end %>