我正在使用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 :(得分:4)
我看到该产品有很多类别。允许用户在产品创建/编辑时指定它们当然是很自然的。描述了一种方法here(通过复选框为产品分配类别)。另一种方法:通常创建产品并允许在其编辑页面上添加/删除类别,例如:
cat_1 [+]
cat_2 [-]
cat_3 [+]
还可以看一下像this one这样的铁路广播,以更漂亮的方式进行。
答案 1 :(得分:0)
首先,要在视图文件中显示类别,请使用以下内容在下拉列表中显示类别
<%= select_tag("category_id[]", options_for_select(Category.find(:all).collect { |cat| [cat.category_name, cat.id] }, @product.category.collect { |cat| cat.id}))%>
然后在产品控制器的create方法中执行类似下面的操作
@product = Product.create(params[:category])
@product.category = Category.find(params[:category_id]) if params[:category_id]
我希望这会对你有所帮助 感谢。
答案 2 :(得分:0)
来自RailsCasts的嵌套模型表教程 也许可以帮助你,或者也许会帮助别人。
答案 3 :(得分:0)
以下是我在_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 %>