2012-05-14 48 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 %>