Rails Button_to not passing model param

喜欢而已 提交于 2019-12-13 06:05:35

问题


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

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

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"}

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"}}

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.


回答1:


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)


来源:https://stackoverflow.com/questions/17458928/rails-button-to-not-passing-model-param

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