我有一个嵌套的用户注册表单。我想为 3 个模型插入数据。User
,Store
和Preference
. 关系是 aUser
has_many :stores
和has_one :preference
。
我遇到的问题是隐藏字段没有出现在我的视图中。我没有正确使用@user.restaurants.build
吗?@user.build_preference
这是我的模型:
class User < ActiveRecord::Base
attr_accessible :email, :full_name, :password, :password_confirmation
has_secure_password
validates_uniqueness_of :email
validates_presence_of :full_name
has_many :stores, :dependent => :destroy
has_one :preference, :dependent => :destroy
accepts_nested_attributes_for :stores
accepts_nested_attributes_for :preference
end
class Store < ActiveRecord::Base
attr_accessible :name, :tagline, :address, :city, :postal, :state, :phone, :hours, :user_id
belongs_to :user
end
class Preference < ActiveRecord::Base
attr_accessible :background_fill, :background_position, :body_color, :body_font, :body_size, :heading_color, :heading_font, :heading_size, :layout, :link_color, :logo_color, :logo_size, :logo_font
belongs_to :user
end
我的用户控制器:
class UsersController < ApplicationController
def new
@user = User.new
@user.stores.build
@user.build_preference
end
我的观点:
<%= form_for @user do |f| %>
<% if @user.errors.any? %>
<div class="error_messages">
<h2>There was an error!</h2>
<ul>
<% @user.errors.full_message.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :full_name %>
<%= f.text_field :full_name, :class => "target", :placeholder => "Your full name", :maxlength => "55", :autofocus => "autofocus" %>
<%= f.label :email %>
<%= f.email_field :email, :class => "target", :placeholder => "example@gmail.com", :maxlength => "55" %>
<%= f.label :password %>
<%= f.password_field :password, :class => "target", :placeholder => "Enter a password", :maxlength => "55" %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, :class => "target", :placeholder => "Enter your password again", :maxlength => "55" %>
<% f.fields_for :stores do |builder| %>
<%= builder.hidden_field :name, value: params[:name] %>
<%= builder.hidden_field :tagline, value: params[:tagline] %>
<%= builder.hidden_field :address, value: params[:address] %>
<%= builder.hidden_field :city, value: params[:city] %>
<%= builder.hidden_field :state, value: params[:state] %>
<%= builder.hidden_field :postal, value: params[:postal] %>
<%= builder.hidden_field :phone, value: params[:phone] %>
<%= builder.hidden_field :hours, value: params[:hours] %>
<% end %>
<% f.fields_for :preference do |builder| %>
<%= builder.hidden_field :layout, value: params[:layout] %>
<%= builder.hidden_field :background_fill, value: params[:background_fill] %>
<%= builder.hidden_field :background_position, value: params[:background_position] %>
<% end %>
<%= f.submit "Create an Account for Free", :class => "button cta" %>
<% end %>
另外,如果有任何帮助,我正在尝试遵循 Railscast 上的本教程:http ://railscasts.com/episodes/196-nested-model-form-part-1
谢谢!