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

﹥>﹥吖頭↗ 提交于 2020-01-23 10:45:08

问题


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



来源:https://stackoverflow.com/questions/5424223/how-to-get-devise-to-work-with-accepts-nested-attributes-for-in-a-has-one-relati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!