0

My form fields are:

 <%= 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 %>

My controller for the form is:

  def signup
    @company = Company.new
    @user = @company.users.build
    if @company.save
      redirect_to :action => 'success'
    else
      render :action => 'signup'
    end
  end

When I save, it says that it fails.

This is the data that was posted (pasted from the rails console):

{"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"}
  1. What is the form unable to save
  2. is there a better way to do this process? (create new Company, then create user linked to that company, all in one form)
4

1 回答 1

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 提供了以下方法accept_nested_attributes_for允许您一次性创建公司和用户。

于 2013-04-26T10:15:59.717 回答