Rails 3 嵌套模型形式
我在使用 Rails 3.1rc4 时遇到了表单中嵌套模型的一些问题。
我目前的模型如下所示:
class Sale < ActiveRecord::Base
attr_accessible :customer_id, :vehicle_id, :sale_date
belongs_to :customer
accepts_nested_attributes_for :customer
end
我
class Customer < ActiveRecord::Base
attr_accessible :dealership_id, :first_name, :last_name, :address1, :email
belongs_to :dealership
has_many :sales
has_many :vehicles, :through => :sales
end
显然已经稍微截断了这些模型,但所有重要信息都在那里。
我正在尝试设置一个销售表单,该表单还允许我创建新客户,因此销售模型中有 accepts_nested_attributes_for :customer
行。
我的表单视图看起来像(再次被截断,只有重要部分):
<%= form_for @sale, :html => {:class => 'fullform'} do |f| %>
<%= f.error_messages %>
<%= field_set_tag 'Customer Details' do %>
<% f.fields_for :customer do |builder| %>
<%= builder.label :first_name %><br>
<%= builder.text_field :first_name %>
<% end %>
<% end %>
<% end %>
我遇到的问题是,当呈现表单时,文本字段和 :first_name 的标签都没有显示 - 没有错误消息,只是没有显示不出现。
我应该提到的是,我在控制器的 new 方法中尝试过使用和不使用 @sale.customer.build ,但似乎没有效果。
谢谢!
谁能建议我做错了什么?
编辑:为了避免疑问,我的销售控制器的新方法如下所示:
def new
@sale = Sale.new
@sale.customer.build
end
I am having some issues with nested models in a form, using Rails 3.1rc4.
I presently have models that look like this:
class Sale < ActiveRecord::Base
attr_accessible :customer_id, :vehicle_id, :sale_date
belongs_to :customer
accepts_nested_attributes_for :customer
end
and
class Customer < ActiveRecord::Base
attr_accessible :dealership_id, :first_name, :last_name, :address1, :email
belongs_to :dealership
has_many :sales
has_many :vehicles, :through => :sales
end
I've obviously truncated these slightly, but all the important info is there.
I am attempting to set up a sale form that will also allow me to create a new customer, hence the accepts_nested_attributes_for :customer
line in the sale model.
My form view looks like (again truncated, only the important part):
<%= form_for @sale, :html => {:class => 'fullform'} do |f| %>
<%= f.error_messages %>
<%= field_set_tag 'Customer Details' do %>
<% f.fields_for :customer do |builder| %>
<%= builder.label :first_name %><br>
<%= builder.text_field :first_name %>
<% end %>
<% end %>
<% end %>
The problem I am having is that neither the text field nor the label for :first_name are showing up when the form is rendered - there is no error message, it just doesn't appear.
I should mention that I have tried both with and without @sale.customer.build
in the new
method of my controller, but it seems to have had no effect.
Thanks!
Can anyone suggest what I am doing wrong?
EDIT: For the avoidance of doubt, my sales controller's new method looks like:
def new
@sale = Sale.new
@sale.customer.build
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
customer_attributes
添加到Sale
模型中的attr_accessible
。又一个错误;替换:
为:
Add
customer_attributes
to yourattr_accessible
in theSale
model.Another mistake; Replace:
With: