0

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 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

brilliant - thanks - in terms of Rails 'best practice', is this considered good practice? Showing my lack of knowledge in this respect...
Well i don't think so, these are params that are coming from outside.. and the solution is also provided here github.com/rails/strong_parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.