How to use scopes in rails to query the database for a subset of information and display it in a view?

StackOverflow https://stackoverflow.com/questions/16264025

  •  13-04-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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

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

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top