如何在一个关系中使用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 true end
User
的company
属性应该不是,所以无论是在控制器中还是在表单中,创建它:
<% user.build_company if user.company.nil? %> <%= f.fields_for :company do |company_form| %> ...
在模型中而不是视图或控制器中执行此操作可能更好。
class User # Blah blah blah def profile super || build_profile end end
Zabba的上述解决方案仅对我有用:
<% @user.build_profile if @user.profile.nil? %>
Othwerise,观点不知道“用户”是什么