Rails Button_to不传递模型参数 [英] Rails Button_to not passing model param

查看:82
本文介绍了Rails Button_to不传递模型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的产品索引页中包含以下内容:

I have the following in my products index page:

<%= button_to "Add", user_order_orderitems_path(user_id: current_user.id, item_id: x.id, order_id: current_user.group.current_order.id), class: "btn btn-mini" %>

从日志中可以看到,我的控制器OK中的Orderitems#create操作正在拾取日志.看起来像:

Which I can see from the logs is being picked up by my Orderitems#create action in my controller ok. This looks like:

def create
  @orderitem = Orderitem.new(orderitem_params)
  if @orderitem.save
     redirect_to items_path
  else
     redirect_to items_path
  end
end

  private

  def orderitem_params
    params.require(:orderitem).permit(:user_id, :order_id, :item_id)
  end

end

在button_to调用中指定的参数正在创建,并在日志中显示为:

The params specified in the button_to call are being created and are showing up in the logs as:

Started POST "/users/1/orders/1/orderitems?item_id=2264" for 127.0.0.1 at 2013-07-03      22:45:24 +0100
Processing by OrderitemsController#create as HTML
  Parameters: {"authenticity_token"=>"blah=",  "item_id"=>"2264", "user_id"=>"1", "order_id"=>"1"}

最后-问题-我的strong_params方法无法处理这些参数,因为我关心的三个参数没有嵌套在以'Orderitem'为键的哈希中.我希望,要使我的create动作正常工作,我需要类似的东西:

Fnally - the problem - my strong_params method can't process these params as the three params I care about are not nested in a hash with 'Orderitem's as a key. I would expect, for my create action to work, I need something like:

      Parameters: {"authenticity_token"=>"blah=", "orderitems"=>{"item_id"=>"2264", "user_id"=>"1", "order_id"=>"1"}}

但是我无法为自己的生活弄清楚如何使用button_to做到这一点-我尝试了form_for,但这也无法正常工作.因此,如何将我的头在砖墙上敲打几天……所以,如何将我的三个ID发布到我的OrderItemsController上,从Products的索引视图中创建操作,却绕过了任何form_for或new操作?有可能吗?

but I can't for the life of me work out how, with button_to I am able to do this - I have tried a form_for, but this also failed to work. Banging my head on a brick wall for a couple of days on this one...So, how can post my three ids to my OrderItemsController create action from an index view for Products but bypassing any form_for or new actions? Is it possible?

请让我知道我是否完全以错误的方式来处理这种情况(将物品添加到购物篮中).

Please let me know if I am approaching this scenario (adding an item to a basket) in completely the wrong way.

推荐答案

通过这种方式,您可以将标准哈希视为

This way you can treat a standard hash as one supported by strong parameters

raw_parameters = {"authenticity_token"=>"blah=",  "item_id"=>"2264", "user_id"=>"1", "order_id"=>"1"}

parameters = ActionController::Parameters.new(raw_parameters)
parameters.permit(:user_id, :order_id, :item_id)

这篇关于Rails Button_to不传递模型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆