0

在我当前的 Rails 应用程序中,我有一个用户模型,它 has_one :user_detail。目前,我无法让表单显示嵌套属性的字段,除非我已经使用 seed.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>

田野不会出现,直到我用这个种子
.rb播种它们

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

我运行 rake db:seed。完成此操作并编辑现有用户后,这些字段就会显示出来,全部填写完毕。但是,在创建用户时,它们不会显示出来。任何想法为什么?

4

2 回答 2

1

我像这样将构建移动到我的控制器并且它有效

def new
  @user = User.new
  @user.build_user_detail
end  
于 2012-04-22T20:37:32.713 回答
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>
于 2012-04-22T06:13:32.900 回答