How to pass parameters in Rails route helper methods?

I know how to pass parameters in a dumb way. For instance,

<%= link_to "Order", new_order_item_path(:item_id => @item.id) %> 

OrderItemsController gets it as params[:item_id] = id .

Problem:

 @order_item = OrderItem.new(params) 

throws an exception (cannot assign protected attributes: action, controller). I can get around this with the following code.

 @order_item = OrderItem.new @order_item.item_id = params[:item_id] 

I know that the controller needs params[:order_item][:item_id] for the new one to work first. My question is: how do I get new_order_item_path to generate the url? I know that this is not a serious problem, but it just seems to me that I do not know how to do it. I tried the search but only got unrelated questions / answers / results.

thanks

+4
source share
2 answers

You did not indicate whether you want to use it or not, but in your model you can make the item_id attribute available as follows:

 class OrderItem < ActiveRecord::Base attr_accessible :item_id ... 

Thus,

 @order_item = OrderItem.new(params) 

will work.

Hope this helps.

0
source

How about this:

 # Controller def get_item_edit_method @order = OrderItem.find("your criteria") #@order = OrderItem.new # if new @item = Item.new() end def post_item_edit_method @order = OrderItem.new(params) # should work now @order.save end # End controller <!-- view --> <% @order.item = @item %> <%= link_to "Order", new_order_item_path(@order) %> <!-- end view --> 
0
source

Source: https://habr.com/ru/post/1412905/


All Articles