views:

79

answers:

1

I have a problem in Rails, I want to show products in each category on a separate page when user clicks on the proper link, categories and products have HABTM relation, I can see the results but I don't want to show them in default pages(routes). Should I create a new routes rule or this can be achieved in controller and view without editing routes ?

This is the code for show.html.erb for category :

<h3><%=h @category.name %></h3>
<div id="category_desc">
    <%=h truncate(@category.description.gsub(/<.*?>/,''),80) %>
</div>
<div id="categories_edit_nav">
    <%= link_to "Edit" , edit_category_path(@category) %>
    <%= link_to "Remove" , category_path(@category) , :confirm => "Are you really want to delete #{@category.name} ?" , :method => "delete" %>
</div>
<div id="category_nav">
    <%= link_to "Create a new Category" , new_category_path %>
</div>

Here I can create a method for category controller like :

  def show_products
    @products_in_category = @category.products.find(:all)    
  end

And use it in show view, but I want to use it in another view, like show_products. Should I create a route for this method ?

A: 

You should use nested resources:

map.resources :categories, :has_many => :products

This will create routes such as /categories/1/products which will direct queries to the products controller and index action where you can use params[:category_id] to render the right result set.

As you experiment with routes, run rake routes to see the results and see http://api.rubyonrails.org/classes/ActionController/Resources.html for more detail.

John Pignata