简体   繁体   中英

Rails Posting to another Controller

I have a controller called orders . In that controller there is a new and create action. Users are able to create an order from the orders/new page, but I would also like them to be able to create an order from the home page. Here is what I've tried to do so far

<%= form_tag :controller => "orders", :action => "create" do %>
  <%= text_field_tag :first_name, 'Test1' %>
  <%= text_field_tag :last_name, 'Test2' %>
  <%= submit_tag %>
<% end %>

However, it is rejecting the information and bringing me back to the orders/new page. The reason it is rejecting it is because I have a validates_presence_of on those two fields and the information is not being passed for some reason.

Any suggestions? Thanks in advance

@Kreek, explained the problem well. Better way than handling those parameters manually would be to change your form like this:

<%= form_for Order.new do |f| %>
  <%= f.text_field :first_name %>
  <%= f.text_fiels :last_name %>
  <%= f.submit %>
<% end %>

You're posting to that controller but the form is generic (not assigned to a model like with form_for) so the params are coming in as just params[:first_name] params[:last_name]. In that case you'd manually have to map those values to a new instance of the Order model.

Contrary to your belief. Your first_name and last_name parameters are actually being passed into the create action. It's just that they are being passed in a way you are not expecting Check in your log file for the create action you will see them there.

Your problem lies in the fact that the fields are not nested inside the order params which is what your create action will be expecting.

I mean, your create action will be expecting params[:order] when in fact you would need params[:first_name] and params[:second_name] in the create action which is not what you want to do.

The solution?

nest the fields inside an order hash like so

  <%= text_field_tag :order[:first_name], 'Test1' %>
  <%= text_field_tag :order[:last_name], 'Test2' %>

Job done :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM