Ruby on Rails:使用accepts_nested_attributes_for不会生成表单的一部分

我有两个模型:用户和个人资料。 我想使用相同的表单同时输入数据。 我正在跟踪关于嵌套模型表格(修订版)的关于转播196#。 问题是,表单的第一部分生成得很好。 这是第二部分(使用field_for),在视图中不显示。 我在stackoverflow中搜索了一个解决方案,并建议以某种方式使用“构建”操作。 但是,由于错误,这不起作用。

如果有人可以解释我如何使其发挥作用,我将非常感激。 我几天来一直在努力解决这个问题。

user.rb class User < ActiveRecord::Base attr_accessible :email, :first_name, :last_name, :orientation, :gender, :password, :password_confirmation, :date_joined, :last_online, :date_of_birth, :location, :profiles_attributes has_one :profiles accepts_nested_attributes_for :profiles, allow_destroy: true has_secure_password validates_confirmation_of :password #.....# end profile.rb class Profile < ActiveRecord::Base attr_accessible :height, :weight belongs_to :user end user/new.html.erb   

Form is invalid







Date of Birth: 1920, :prompt => { :day => 'day', :month => 'month', :year => 'year' }) %>









编辑:user_controller中的新动作:(你可以看到它非常标准)

  def new @user = User.new respond_to do |format| format.html # new.html.erb format.json { render json: @user } end end 

我想你需要

 has_one :profile 

在您的用户模型中。

让表格做

  fields_for :profile 

并在您的users_controller中做

 @user = User.new @user.build_profile 

has_one关系与has_many的工作方式略有不同 – 请参阅http://guides.rubyonrails.org/association_basics.html#has_one-association-reference