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
scope :appetizers, -> { where(post.category.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”.
Title | Body | Category |
---|---|---|
<%= app.title %> | <%= app.body %> | <%= app.category.name%> |
I am getting an “undefined method” error. I have tried searching for an
example here that explains what is a correct solution. I also tried
creating a method in the Post model like this:
def appetizers_list
@appetizer_list = Post.appetizers.all
end
Then call the method in the view:
<% @appetizer_list.each do |app| %>
Obviously I am confusing what needs to be done after creating the scope
and
how to get the view to “see” it. Or if I need a scope at all and it can
be
done in a more simple way.
So is there a best practices for retrieving subsets of data in rails and
displaying them to the view?