Ruby on rails 如何让Desive在has one关系中使用accepts_nested_attributes_?

Ruby on rails 如何让Desive在has one关系中使用accepts_nested_attributes_?,ruby-on-rails,ruby-on-rails-3,devise,nested-attributes,has-one,Ruby On Rails,Ruby On Rails 3,Devise,Nested Attributes,Has One,我正试图让我的用户表单也允许用户填写他们的公司档案,同时通过表单_。由于某些原因,它没有显示公司字段。这是我的控制器和布局代码 class User < ActiveRecord::Base attr_accessible :company_attributes has_one :company accepts_nested_attributes_for :company end class Company < ActiveRecord::Base belongs

我正试图让我的用户表单也允许用户填写他们的公司档案,同时通过表单_。由于某些原因,它没有显示公司字段。这是我的控制器和布局代码

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 %>
class用户true
结束


用户的
company
属性不应为-
nil
,因此无论是在控制器中还是在表单中,都应创建它:

<% user.build_company if user.company.nil? %>
<%= f.fields_for :company do |company_form| %>
...

...

上述来自Zabba的解决方案仅适用于我:

<% @user.build_profile if @user.profile.nil? %>


否则,视图不知道什么是“用户”

在模型中这样做可能比在视图或控制器中更好

class User
  # Blah blah blah
  def profile
    super || build_profile
  end
end

可能应该在用户初始化后这样做谢谢!我正在与Deviate合作,我不知道我能做一个
资源。在RegistrationController中构建_profile
,所以这非常有效。