nested_attributes字段未显示

时间:2012-04-22 06:04:29

标签: ruby-on-rails nested-attributes

在我当前的rails应用程序中,我有一个用户模型has_one:user_detail。目前,我无法获取表单来显示嵌套属性的字段,除非我已经使用seeds.rb文件播种。

这是我的用户模型

class User < ActiveRecord::Base
  has_one :user_detail, :dependent => :destroy
  accepts_nested_attributes_for :user_detail
  attr_accessible :email, :password, :password_confirmation, :access_level, :first_name, :last_name, :user_detail_attributes
  has_secure_password
end

和我的UserDetail模型

class UserDetail < ActiveRecord::Base
  belongs_to :user
end

和我的表格

<%= form_for [:admin, @user] do |f| %>
  <p><%= f.text_field(:name, :placeholder => 'Name')%></p>
  <p><%= f.label(:email) %></p>
  <p><%= f.email_field(:email, :placeholder => 'Your Email')%></p>
  <p><%= f.password_field(:password, :placeholder => 'Choose a password') %></p>
  <p><%= f.password_field(:password_confirmation, :placeholder => 'Confirm Password') %></p>

    <%= f.fields_for :user_detail do |u| %>
      <p><%= u.text_field(:country, :placeholder => 'Country') %></p>
      <p><%= u.text_field(:state, :placeholder => 'State') %></p>
      <p><%= u.text_field(:city, :placeholder => 'City') %></p>
      <p><%= u.text_field(:phone, :placeholder => 'Phone') %> </p>
    <% end %>

  <p><%= submit_tag("Add Owner") %></p>

在我用这个种子播种之前,这些字段不会显示出来 seeds.rb

UserDetail.delete_all
owner1detail = UserDetail.create(:zip => "84770",
                              :country => "US",
                              :state => "Ut",
                              :city => "St. George",
                              :user_id => owner1.id
                             )

我运行rake db:seed。一旦我执行此操作并编辑现有用户,字段就会显示,所有字段都已填写。但是,在创建用户时,他们不会显示。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我将构建移动到我的控制器,就像这样工作

def new
  @user = User.new
  @user.build_user_detail
end  

答案 1 :(得分:0)

尝试预建。

<%= form_for [:admin, @user] do |f| %>
  <p><%= f.text_field(:name, :placeholder => 'Name')%></p>
  <p><%= f.label(:email) %></p>
  <p><%= f.email_field(:email, :placeholder => 'Your Email')%></p>
  <p><%= f.password_field(:password, :placeholder => 'Choose a password') %></p>
  <p><%= f.password_field(:password_confirmation, :placeholder => 'Confirm Password') %></p>

    <% @user.user_detail.build if @user.user_detail.nil? %>

    <%= f.fields_for :user_detail do |u| %>
      <p><%= u.text_field(:country, :placeholder => 'Country') %></p>
      <p><%= u.text_field(:state, :placeholder => 'State') %></p>
      <p><%= u.text_field(:city, :placeholder => 'City') %></p>
      <p><%= u.text_field(:phone, :placeholder => 'Phone') %> </p>
    <% end %>

  <p><%= submit_tag("Add Owner") %></p>