Reputation: 15374
I have a posts model and a category model
class Category < ActiveRecord::Base
has_many :posts
attr_accessible :name
end
Class Post < ActiveRecord::Base
belongs_to :category
attr_accessible :comments, :title, :category_id, :user_id, :photo
end
What I am trying to do is reuse (apply the DRY principle) when using the @posts instance variable in my app. I think im getting in a muddle somewhere. Each post has its own category.
In my view i have all the categories listed
<% @categories.each do |c, v| %>
<li><%= link_to c, blog_path(:name => c) %></li>
<% end %>
Controller
def blog
if params[:month]
date = Date.parse("1 #{params[:month]}") # to get the first day of the month
@posts = Post.where(:created_at => date..date.end_of_month) # get posts for the month
elsif params[:name]
@posts = Post.where(:name => params[:name])
else
@posts = Post.all(:order => "created_at DESC")
end
@latest = Post.latest_posts
@posts_by_month = Post.all.group_by { |post| post.created_at.strftime("%B %Y") }
#Category Section down side of page
@categories = Category.all.group_by { |c| c.name }
end
What i want to achieve is to click a category and then it will display all posts that belong to that category, at the moment when clicking a category link i get
Mysql2::Error: Unknown column 'posts.name' in 'where clause': SELECT `posts`.* FROM `posts` WHERE `posts`.`name` = 'Ruby'
Upvotes: 0
Views: 2187
Reputation: 6015
You can do it symply by
<% @categories.each do |c| %>
<li><%= link_to c, blog_path(:category_id => c.id) %></li>
<% end %>
in controller
def blog
category_id = params[:category_id]
@category = Category.find(category_id)
@posts = @category.posts.order("posts.created_at DESC")
end
Upvotes: 2
Reputation: 29094
You have to replace this line
@posts = Post.where(:name => params[:name])
with
category = Category.where(:name => params[:name]).first
@posts = category.posts
Upvotes: 1