简体   繁体   English

Rails发布到另一个控制器

[英]Rails Posting to another Controller

I have a controller called orders . 我有一个称为orders的控制器。 In that controller there is a new and create action. 在该控制器中,有一个newcreate动作。 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. 但是,它拒绝了该信息并将我带回到orders/new页面。 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. 之所以拒绝它,是因为我在这两个字段上都有一个validates_presence_of ,并且由于某种原因信息没有被传递。

Any suggestions? 有什么建议么? Thanks in advance 提前致谢

@Kreek, explained the problem well. @Kreek,很好地解释了这个问题。 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]. 您要发布到该控制器,但是表单是通用的(未分配给像form_for这样的模型),因此参数仅以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. 在这种情况下,您将必须手动将这些值映射到Order模型的新实例。

Contrary to your belief. 与您的信念相反。 Your first_name and last_name parameters are actually being passed into the create action. 您的first_name和last_name参数实际上已传递到create动作中。 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. 只是它们以您不期望的方式传递,因此请在日志文件中检入create操作,您将在此处看到它们。

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. 我的意思是,您的create动作将期望有params [:order],而实际上您在create动作中将需要params [:first_name]和params [:second_name]而不是您想要的。

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 :) 任务完成 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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