Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 883
BrendanC Avatar asked Aug 05 '09 07:08

BrendanC


2 Answers

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 %>
like image 58
Garrett Avatar answered Sep 30 '22 11:09

Garrett


For the "magic" form <=> model mapping form_for is used. (http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html)

If you need something out of the current model try using http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html

With that you can add tags separate from the model, eg

radio_button_tag

inside the form_for block

like image 31
Peter Lind Avatar answered Sep 30 '22 12:09

Peter Lind