views:

72

answers:

1

So I'm finally starting to use rest in rails.

I want to have a select_tag with product categories and when one of the categories is selected I want it to update the products on change.

I did this before with

<% form_for :category, :url => { :action => "show" } do |f| %>
<%= select_tag :id, options_from_collection_for_select(Category.find(:all), :id, :name),
{ :onchange => "this.form.submit();"} %>
<% end %>

however now it doesn't work because it tries to do the show action.

I have two controllers 1) products 2) product_categories

products belongs_to product_categories with a has_many

How should I do this.

Since the products are listed on the products controller and index action should I use the products controller or should I use the product_categories controller to find the category such as in the show action and then render the product/index page.

But the real problem I have is how to get this form or any other option to work with restful routes.

A: 

First routes - you need to define product as resource, so you would have helper methods: edit_product_path(@product), new_product_path and so on:

# routes.rb
map.resource :products

Then controller - standard resource controller:

# products_controller.rb
def edit
  @product = Product.find(params[:id])
end

def update
  @product = Product.find(params[:id])
  if @product.update_attributes(params[:product])
    flash[:notice] = "Product updated"
    redirect_to @product
  else
    render :edit
  end
end

And now view - it's easier to user form_for to build form for specific object (new or existing). For new object it points by default to #create action on controller for this resource and for existing points to #update. You can always override this paths if needed:

# products/new.html.erb
<% form_for @product do |f| %>
  <%= f.select :product_category, Category.all, {}, {:onchange => "this.form.submit();" %>
<% end %>
MBO