跟进此主题: (Rails) How to display child records (one-to-many) in their parent's form?
我正在创建一个可能包含许多产品的类别。因此,我使用Formtastic作为用户Chandra Patni建议的。但是当我将attr_accessible添加到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
这是category.rb:
class Category < ActiveRecord::Base
attr_accessible :name
has_many :products
end
在我添加了attr_accessible:category_id,:name之后,验证变得疯狂,无论我输入什么,它都会在文本值中将其视为null。但是在我删除attr_accessible:category_id后,:name all stuff。
还有一件事,在products / new.html.erb中,我创建了这个来输入产品信息,
<% 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 %>
但我发现它返回:category id而不是category name。我该怎么办? Thx在先进。
答案 0 :(得分:1)
您需要为attr_accessible
添加其他属性以供rails执行批量分配。
attr_accessible :category_id, :name, :title, :price, :photoPath
Rails只会为attr_accessible
(白名单)中指定的属性进行质量分配(如果有)。从安全的角度来看是必要的。 Rails还提供了一种通过attr_protected
方法将批量分配列入黑名单的方法。
如果您的name
模型中包含Category
属性,则会看到下拉类别。请参阅this和this。
class Category < ActiveRecord::Base
has_many :products
attr_accessible :name
end