I'm using rails to create a new product and want to add a category to every product.
I have three tables: product, category, and categorizations (which stores the relationship between products and categories). I'm trying to use nested attributes to manage the creation of the categorizations, but unsure how my controller and view/form should be updated so that new products also update the categorizations table.
Here are my models:
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
Here is my new product controller:
def new
@product = Product.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @product }
end
end
And here is my view form:
<%= 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 %>
How should I update my controller so that both the product and the categorization tables are updated when a new product is added? How do I update my view file so that the categories appear in a drop down menu?
I see that product has_many categories. It's naturally to allow the user to specify them at product creation/edition. One approach is described here (via checkboxes to assign categories to your product). Another way: create product as usually and allow adding/removing categories on its edit page, like:
cat_1 [+]
cat_2 [-]
cat_3 [+]
Also take a look at Railcasts, like this one for doing it on a more beautiful way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With