How to get devise to work with accepts_nested_attr

2019-05-13 16:34发布

问题:

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 %>

回答1:

The company attribute of the User should be not-nil, so either in the controller or in the form, create it:

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


回答2:

It might be better to do this in the model rather than the view or the controller.

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


回答3:

The above solution from Zabba only worked for me with:

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

Othwerise, the view had no idea what "user" is