0

I am a beginner and I appreciate an answer to help me understand where my knowledge gap is:

The app is to display a post. The posts belong to a category (appetizers, entrees...) My thought was to use scopes to display all the appetizers on the posts in one view and then have the entrees in another view and so on.

The models:

class Post < ActiveRecord::Base
attr_accessible :body, :category_id, :title

belongs_to :category

#wrong: scope :appetizers, -> { where(post.category.name => "Appetizers")}

#corrected scope per Frederick Cheung     
scope :appetizers, ->{joins(:category).where(:categories => {:name => "Appetizers"})}
end


class Category < ActiveRecord::Base
attr_accessible :name

has_many :posts
end     

In the view I want to loop through the posts where the category name is "Appetizers".

<table>
  <tr>
    <th>Title</th>
    <th>Body</th>
    <th>Category </th>
  </tr>

  <% @post.each do |post| %>
  <tr>
    <td><%= post.title %></td>
    <td><%= post.body %></td>
    <td><%= post.category.name%></td>
  </tr>
  <% end %>

  <%= link_to "Appetizers", appetizers_posts_path %>

 </table> 

This requires me to set a route:

  get 'posts/appetizers' => 'posts#appetizers', :as => 'appetizers_posts'

I also have to add to the post controller:

 def appetizers
  @posts = Post.appetizers
   render 'index' 
 end

This gets me a page with results I want but as commented below it is kind of messy and will not scale very well if you have a lot of categories.

I am looking for a cleaner way to do it. Any suggestions would be great.

akkdio
  • 573
  • 2
  • 5
  • 13
  • I edited the original to use the method phron suggested. I am still looking for a cleaner way. – akkdio May 01 '13 at 14:21

1 Answers1

1

I found this tutorial very helpful, hope it will help you too

http://www.jacopretorius.net/2012/02/scopes-in-rails.html

Cheers

phron
  • 1,795
  • 17
  • 23
  • thanks I looked at the link and its very clear on what its doing. My confusion/question here is based on the thought I should be able to scope a query and then have it displayed in a view through calling it somehow in the model and then pulling it into the view without the controller knowing anything? – akkdio Apr 28 '13 at 16:23
  • I got the solution to work using jocopretorius's method with controllers but it seems "dirty" in that I have to clutter the controller... Isn't there a more elegant way? – akkdio Apr 29 '13 at 14:10