One to many relationship in ROR using Formtastic
following up with this topic: (Rails) How to display child records (one-to-many) in their parent's form?
I am creating a category that may have many products. So, I use the Formtastic as user Chandra Patni suggested. But I find there is a problem when I added attr_accessible to the product.rb.
class Product < ActiveRecord::Base
validates_presence_of :title, :price
validate开发者_StackOverflows_numericality_of :price
validates_uniqueness_of :title
attr_accessible :category_id, :name
belongs_to :category
end
and this is the category.rb:
class Category < ActiveRecord::Base
attr_accessible :name
has_many :products
end
After I added the attr_accessible :category_id, :name , the validation gets crazy, no matter I type, it treats me as null in the text value. But after I remove the attr_accessible :category_id, :name all stuff works.
One more thing, in the products/new.html.erb , I created this to input the product information,
<% semantic_form_for @product do |f| %>
<% f.inputs do %>
<%= f.input :title %>
<%= f.input :price %>
<%= f.input :photoPath %>
<%= f.input :category %>
<% end %>
<%= f.buttons %>
<% end %>
But I find that it return the :category id instead of the category name. What should I do? Thx in advanced.
You will need to add other attributes to attr_accessible
for rails to perform mass assignment.
attr_accessible :category_id, :name, :title, :price, :photoPath
Rails will only do mass assignment for attributes specified in attr_accessible
(white list) if you have one. It is necessary from security point of view. Rails also provides a way to blacklist mass assignments via attr_protected
method.
You should see a drop down for category if you have name
attribute in your Category
model. See this and this.
class Category < ActiveRecord::Base
has_many :products
attr_accessible :name
end
精彩评论