ユーザーとプロファイルの2つのモデルがあります。同じフォームを使用して、両方に同時にデータを入力したいと思います。Nested Model Form(改訂版)についてrailscast 196#をフォローしていました。問題は、フォームの最初の部分がうまく生成されていることです。ビューに表示されないのは2番目の部分(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_for @user do |f| %>
<% if @user.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in @user.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :gender, "I am a:" %><%= f.select :gender, options_for_select([["Man", "Male"], ["Woman", "Female"]]) %><br />
<%= f.label :orientation, "Sexsual Orientation" %><%= f.select :orientation, options_for_select([["Straight", "Straight"], ["Gay", "Gay"], ["Bi","Bi"]]) %><br />
<%= f.label :first_Name %><br /><%= f.text_field :first_name %><br />
<%= f.label :last_name %><br /><%= f.text_field :last_name %><br />
Date of Birth:<%= f.date_select( :date_of_birth, :start_year => 1920, :prompt => { :day => 'day', :month => 'month', :year => 'year' }) %><br />
<%= f.label :location %><br /><%= f.text_field :location %><br />
<%= f.label :email %><br /><%= f.text_field :email %><br />
<%= f.label :password %><br /><%= f.password_field :password %><br />
<%= f.label :password_confirmation %><br /><%= f.password_field :password_confirmation %><br />
<%= f.fields_for :profiles do |builder| %>
<fieldset>
<%= builder.label :height, "My height is: (cm)" %><%= builder.text_field :height %><br />
<%= builder.label :weight, "My weight is: (kg)" %><%= builder.text_field :weight %>
</fieldset>
<% end %>
<%= f.submit "Next" %>
<% end %>
<%= link_to 'Back', users_path %>
編集:user_controllerの新しいアクション:(ご覧のとおり、かなり標準的です)
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end