newbie question: Why the selected value from dropdown menu does not pass to my controller?
I have a model "MyObject" which contains a property called 'color', this property value is selected from the list of COLORS=['red','black','yellow']. In my application, I have get one instance of "MyObject" from database and show it on the page as a row. I use the 'select' form helper in rails 3, and allowed user to select the color from a dropdown menu.
I used the form helper in this way:
select("myobject", COLORS, { :include_blank => false })
,
On the view page, I successfully get the colors as a drop down menu with the default value as the selected one.
BUT, when I select another color from the menu and press save button, the "myobject" passed to my controller always hold the default color value instead of the selected one, why??
I use button_to("save", myobject_path(myobject), :method=>:put)
which will pass the object to my control开发者_如何学Goler.
in side my controller, update method:
class MyobjectsController < ApplicationController
...
def update
@myobject = myobject.find(params[:id])
if @myobject.update_attributes(params[:myobject])
puts @myobject.color #always get default value
redirect_to myobject_path
else
redirect_to myobject_path
end
end
...
end
Anybody can explain me why I always get default color value instead of the selected one?
Without seeing the full view code I'm not sure of this, but most likely it's that your form that contains the <select>
isn't actually being submitted and that button_to
is simply creating its own form and submiting. You should put the myobject_path(myobject), :method => :put
on the form itself, not the submit button. And don't use button_to
for this, use submit_tag
or something.
精彩评论