开发者

How to get devise to work with accepts_nested_attributes_for in a has one relationship?

开发者 https://www.devze.com 2023-02-19 07:41 出处:网络
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 co

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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消