0

I am trying to achieve an unordered list of "Categories" in which if you click on a particular Category, all the photos(jags) that belong to that Category show on the screen. My view that includes the categories is:

<div id = "Categories">
<h2>Categories</h2>
<ul><% @cat.each do |c| %>
    <li><%=link_to c.name, c,:controller => "category", :action => "show"  %>
    </li>
<% end %>
</ul>

my Category controller is:

def show
@jags = Jag.where("category_id = params[:id]")
   if @jags.empty?
     flash[:notice] = "No jags in this Category"
    end
end

and lastly my show view is:

<%= render 'nav' %>
<div><% @jags.each do |j| %>
<%=  image_tag j.image_url(:thumb)%>
<% end %>
</div>

The problem i am having is that I dont know how do i pass on my "particular category"(c) in the first view to the Category controller.

I tried making c an instance variable(@c) which apparently i cant do[formal argument cannot be an instance variable '); @cat.each do |@c| ;@output_buffer.safe_concat('].

If I run this code I get an SQLlite error[SQLite3::SQLException: near "[:id]": syntax error: SELECT COUNT(*) FROM "jags" WHERE (category_id = params[:id])].

nupac
  • 2,459
  • 7
  • 31
  • 56

2 Answers2

1

If you use RESTful controllers this should be enough:

<div id = "Categories">
<h2>Categories</h2>
<ul>
<% @cat.each do |c| %>
    <li><%=link_to c.name, c  %></li>
<% end %>
</ul>
Tolik Kukul
  • 1,996
  • 16
  • 26
  • I dont understand. How will link_to know where it is supposed to link the c.name to? – nupac Dec 17 '12 at 17:27
  • we pass `c` which is `Category` object – Tolik Kukul Dec 17 '12 at 17:28
  • a couple of things i dont understand, 1. how does it know it is supposed to go the show action, 2. how can i pass on 'c' because its not an instance variable – nupac Dec 17 '12 at 17:31
  • Does my example works? everything you should know for now is described here: http://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects – Tolik Kukul Dec 17 '12 at 17:33
  • I get this error "uninitialized constant CategoriesController" – nupac Dec 17 '12 at 17:33
  • hm. your controller name is Category not Categories which is not ok. Try to work with rails scaffolding, that will give you more understanding. Good point to start here: http://guides.rubyonrails.org/getting_started.html – Tolik Kukul Dec 17 '12 at 17:37
  • I've got it to work and I understand Rails a little better. Thanks – nupac Dec 17 '12 at 19:00
1

Seeing as you're getting the ID for the Category in the controller, then you can just do

@category = Category.find params[:id]

in your controller. Also, clean up your link_to helper as per below.

Mike Campbell
  • 7,921
  • 2
  • 38
  • 51