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

三世轮回 提交于 2019-12-17 15:36:50

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/1231608/rails-user-input-for-multiple-models-on-a-single-form-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!