如何让设计在一个关系中与accepts_nested_attributes_for一起工作?
我试图让我的用户表单也允许用户通过 form_for 同时填写他们的公司资料。由于某种原因,它没有显示公司字段。这是我的控制器和布局的代码。
class User < ActiveRecord::Base
attr_accessible :company_attributes
has_one :company
accepts_nested_attributes_for :company
end
class Company < ActiveRecord::Base
belongs_to :user
# Validation
validates :name, :presence => true
end
<%= f.fields_for :company do |company_form| %>
<div class="field">
<%= company_form.label :name, "Company Name" %><br />
<%= company_form.text_field :name %>
</div>
<% end %>
I am trying to get my user form to also allow the user to fill out their company profile at the same time via form_for. For some reason it is not showing the company fields. Here is my code for the controller and layouts.
class User < ActiveRecord::Base
attr_accessible :company_attributes
has_one :company
accepts_nested_attributes_for :company
end
class Company < ActiveRecord::Base
belongs_to :user
# Validation
validates :name, :presence => true
end
<%= f.fields_for :company do |company_form| %>
<div class="field">
<%= company_form.label :name, "Company Name" %><br />
<%= company_form.text_field :name %>
</div>
<% end %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
User
的company
属性不应该nil
,因此无论是在控制器还是在表单中,创建它:The
company
attribute of theUser
should be not-nil
, so either in the controller or in the form, create it:在模型中而不是在视图或控制器中执行此操作可能更好。
It might be better to do this in the model rather than the view or the controller.
Zabba 的上述解决方案仅适用于我:
Othwerise,视图不知道“用户”是什么
The above solution from Zabba only worked for me with:
Othwerise, the view had no idea what "user" is