views:

286

answers:

1

following up with this topic: http://stackoverflow.com/questions/1992094/one-to-many-relationship-in-ror

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
  validates_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.

+1  A: 

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
Chandra Patni
the web site only have <%= f.input :category, :include_blank => false %> than they can return the category name, but I can't do so, I only get the Object id.
Ted Wong
Do you have name attribute for category?
Chandra Patni
sorry, I have type wrong. thx a lot.
Ted Wong