TopCat TopCat - 4 months ago 18
Ruby Question

Ruby on Rails Rails: ActiveRecord object not receiving parameters from form

I've been working through "Agile Web Development with Rails" and have come across an issue.

I've been having issues with saving/retrieving data selected from a drop down menu. I have possible payment methods stored in a database table, and I have a drop down menu to select the desired payment method.

<div class="field">
<%= f.label :payment_type_id %><br>
<%= f.select :payment_type_id, options_from_collection_for_select(@payment_types,:id,:method), prompt: 'Select Payment Method'%>
</div>


My "create" action in the Orders controller

def create
@order = Order.new(order_params)
@order.add_line_items_from_cart(current_cart)
respond_to do |format|
if @order.save
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
OrderNotifier.received(@order).deliver
format.html { redirect_to store_url, notice: 'Order has been placed' }


Everything gets saved apart from the payment_type_id foreign key, I know this because I've looked in the tables.

Any help would be greatly appreciated.

Thanks.

Answer

A good place to start is always checking your require/permit method. In this case it looks like it is named order_params - if you haven't included a field in that, then it will never be saved.

As mentioned in another comment, you can also check if this is the case, by reading through your server logs - you will often get a message about Unpermitted params - these are the params being discarded.

Sometimes it's because the fields in the form aren't quite named correctly, so they're not coming through the way you'd expect - again looking in the server logs is a good idea as it will tell you what params are coming through and what the structure of them is and thus you have a chance of fixing them.

Here is a random example of a server log for a "widget" form and what it looks like when some of these errors occur:

Started POST "/widgets" for 127.0.0.1 at 2013-04-10 00:16:37 -0700
Processing by WidgetsController#create as HTML<br>
Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"ipxBOLOjx68fwvfmsMG3FecV/q/hPqUHsluBCPN2BeU=",
 "widget"=>{"name"=>"Widget 1", "colour"=>"Blue"}, "size"=>"large"
}
Unpermitted parameters: colour

In this example: the "size" property is not correctly placed as being a parameter for a widget... also the "colour" property is being rejected. So you'd say that you need to add "colour" to the require/permit section, and move the size field so that it is properly inside the widget-form.

Comments