我正在使用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 %>
我應該如何更新我的控制器以便在添加新產品時更新產品和分類表?如何更新我的視圖文件,以便類別顯示在下拉菜單中?
*,但不知道該如何我...視圖/表單應該更新* - 我們也不知道,因爲你沒有暴露它們。 – jdoe
Hi @jdoe - 我在這裏添加了視圖文件。只是由rails生成的命令創建的標準。 –