catbones
catbones

Reputation: 29

rails display all posts with current category id

I'm trying to display posts that have a :cat_id of current category and I'm not clicking the right things together I'm guessing. Let me explain;

Each post has a cat_id in DB, it will be the ID of the category. On my page, if I click on a category the url changes to something like; http://domain.com/cat/1 and it should display all posts category 1 has.

So far I've tried the following with no success;

CONTROLLER

def show
    @cat = Cat.find(params[:id])
    @cat = Cat.all
    @posts = @cat.posts
end

VIEW

<div id="posts">
<% @posts.limit(50).each do |post| %>
    <h1><%= post.title %></h1>
<% end %>
</div>

No success with the above.

I've also tried;

CONTROLLER

def show
    @cat = Cat.find(params[:id])
    @post = Post.find(params[:id])
end

VIEW

<div id="posts">
<% @bin.posts(:cat_id => cat.id).limit(50).each do |post| %>
    <h1><%= post.title %></h1>
<% end %>
</div>

No luck either. I know I'm close, just can't wrap my head around it.

Upvotes: 0

Views: 2760

Answers (2)

Mike Heijmans
Mike Heijmans

Reputation: 439

I assume you that you are using a proper model association.

If you have setup your model so that a post belongs to a category and a category has many posts like this:

Post Model:

class Post < ActiveRecord::Base
   belongs_to :cat
end

Cat Model:

class Cat < ActiveRecord::Base
   has_many :posts
end

Then you just need to use that association like this:

Controller:

def show
  @cat = Cat.find(params[:id])
  @posts = @cat.posts
end

View:

<div id="posts">
  <% for post in @posts do %>
    <h1><%= post.title %></h1>
  <%end%>
</div>

Upvotes: 0

jvperrin
jvperrin

Reputation: 3368

Try this, all I did was remove the overwriting of @cat with Cat.all and move the post limit to the controller with the rest of the query:

CONTROLLER

def show
    @cat = Cat.find(params[:id])
    @posts = @cat.posts.limit(50)
end

VIEW

<div id="posts">
<% @posts.each do |post| %>
    <h1><%= post.title %></h1>
<% end %>
</div>

Upvotes: 2

Related Questions