Rails を使用して新しい製品を作成しており、すべての製品にカテゴリを追加したいと考えています。
製品、カテゴリ、およびカテゴリ (製品とカテゴリの関係を格納する) の 3 つのテーブルがあります。ネストされた属性を使用して分類の作成を管理しようとしていますが、新しい製品でも分類テーブルを更新できるように、コントローラーとビュー/フォームを更新する方法がわかりません。
ここに私のモデルがあります:
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 %>
新しい製品が追加されたときに製品と分類テーブルの両方が更新されるようにするには、コントローラーをどのように更新すればよいですか? ビュー ファイルを更新して、カテゴリがドロップダウン メニューに表示されるようにするにはどうすればよいですか?