Reputation: 1772
How can I pass the selected value from a drop down list to the controller in Ruby?
<select>
<option value="0">New</option>
<option value="1">SubCategory1</option>
<option value="2">SubCategory2</option>
<option value="3">SubCategory3</option>
</select>
still i having a problem here is my code
<select name="category_id">
<option value="0">New Category</option>
<% for category in categories %>
<option value="<%= category.id %>"><%= category.name %></option>
<% end %>
</select>
def create
if params[:category_id] == 0
@category = Category.new(params[:category])
respond_to do |format|
if @category.save
end
else
@subcategory = Subcategory.new(params[:subcategory])
respond_to do |format|
if @subcategory.save
....
end
end
end
end
the params[:category_id] == 0 is never executed because is not passing the value 0 to the controller. How i can solve it?
Upvotes: 1
Views: 6123
Reputation: 1160
Let's say you have a Product model and you want to store the category_id in it. In your form, you would do like this.
<select name="product[category_id]">
<option value="0">New</option>
<option value="1">SubCategory1</option>
<option value="2">SubCategory2</option>
<option value="3">SubCategory3</option>
</select>
Then you can get it in controller with params[:product][:category_id]
I suggest you use form helper gems like Simple Form. It makes your life much easier.
Upvotes: 1
Reputation: 176352
Give a name attribute to the select. Once the form is submitted, you'll find the value of the selected option in the params
Hash.
For example
<select name="category_id">
<option value="0">New</option>
<option value="1">SubCategory1</option>
<option value="2">SubCategory2</option>
<option value="3">SubCategory3</option>
</select>
params[:category_id]
Upvotes: 8