我的表单字段是:
<%= form_tag signup_path, :class=>"no-ajax form-signin" do %>
<fieldset>
<legend>Company</legend>
<div class="field">
<label>Company Name</label>
<%= text_field :company, :name, :class => "input-block-level" %>
</div>
<%= hidden_field :company, :accounttype_id, :value => 2 %>
</fieldset>
<fieldset>
<legend>User</legend>
<div class="field">
<label>First Name</label>
<%= text_field :user, :first_name, :class => "input-block-level" %>
</div>
<div class="field">
<label>Last Name</label>
<%= text_field :user, :last_name, :class => "input-block-level" %>
</div>
<div class="field">
<label>Email</label>
<%= text_field :user, :email, :class => "input-block-level" %>
</div>
<div class="field">
<label>Role</label>
<%= text_field :user, :role_id, :value => 2 %>
</div>
</fieldset>
<fieldset>
<div class="field">
<label>Password</label>
<%= text_field :user, :password, :class => "input-block-level" %>
</div>
<div class="field">
<label>Confirm Password</label>
<%= text_field :user, :password_confirmation, :class => "input-block-level" %>
</div>
</fieldset>
<div class="form-actions">
<%= submit_tag 'Sign Up', :class => "btn btn-large btn-success btn-block" %>
</div>
<% end %>
表单的控制器是:
def signup
@company = Company.new
@user = @company.users.build
if @company.save
redirect_to :action => 'success'
else
render :action => 'signup'
end
end
当我保存时,它说它失败了。
这是发布的数据(从rails控制台粘贴):
{"utf8"=>"✓", "authenticity_token"=>"9y4JeSvm34P05FBKbP3D3aToHlwejFZBkSyPbmGMJrk=", "company"=>{"name"=>"Test Co", "accounttype_id"=>"2"}, "user"=>{"first_name"=>"Andy", "last_name"=>"Bernard", "email"=>"andy@testco.com", "role_id"=>"2", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"}
答案 0 :(得分:2)
控制器中的signup
操作未保存@company
,因为调用Company.new
时未传递任何属性。
@company = Company.new(params[:company])
将传递参数"company"=>{"name"=>"Test Co", "accounttype_id"=>"2"}
。
同样适用于"user"=>{...}
:
@user = @company.users.build(params[:user])
对于一体化表单,Rails提供了以下方法accepts_nested_attributes_for,允许您一次创建公司和用户。