How can I pass the selected value from a drop-down list to the controller in Ruby?

advertisements

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?


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]