Rails - User Input for Multiple models on a single form - How

BrendanC picture BrendanC · Aug 5, 2009 · Viewed 13k times · Source

This is basically a nested form question, albeit with only one field that belongs to a parent model. My data entry form collects data for a model - however I also need to collect one other a data element/value (UserID) that actually goes into a parent record that will be created with the detail record.

AFAIK Rails expects each form field to map to a model and I need to create an unbound data input field that I will use separately.

How can I override this default behaviour and create a'free form/unbound field'?

TIA, BC

Answer

Garrett picture Garrett · Aug 5, 2009

Heres something from my own app:

Access it by:

params[:company] and params[:user]

Controller:

@company = Company.new
@user = User.new

View:

<% form_for @company, :url => companies_path do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :website %><br />
    <%= f.text_field :website %>
  </p>
<hr />
    <% fields_for @user do |u| %>
    <p>
        <%= u.label :email %><br />
    <%= u.text_field :email %>
    </p>
    <p>
        <%= u.label :username %><br />
    <%= u.text_field :username %>
    </p>
    <p>
        <%= u.label :password %><br />
    <%= u.password_field :password %>
    </p>
  <p>
    <%= u.label :password_confirmation %><br />
    <%= u.password_field :password_confirmation %>
  </p>
    <% end %>
  <p>
        <%= f.submit "Submit" %>
    </p>
<% end %>