0

我有一个帖子模型和一个类别模型

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

我要做的是在我的应用程序中使用 @posts 实例变量时重用(应用 DRY 原则)。我想我在某个地方陷入了混乱。每个帖子都有自己的类别。

在我看来,我列出了所有类别

<% @categories.each do |c, v| %>
 <li><%= link_to c, blog_path(:name => c) %></li>
<% end %>

控制器

 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

我想要实现的是单击一个类别,然后它将显示属于该类别的所有帖子,此时单击我得到的类别链接

Mysql2::Error: Unknown column 'posts.name' in 'where clause': SELECT `posts`.* FROM `posts`  WHERE `posts`.`name` = 'Ruby'
4

2 回答 2

2

你可以简单地做到这一点

<% @categories.each do |c| %>
 <li><%= link_to c, blog_path(:category_id => c.id) %></li>
<% end %>

在控制器中

def blog

  category_id = params[:category_id]
  @category = Category.find(category_id)
  @posts = @category.posts.order("posts.created_at DESC")

end
于 2013-08-02T12:43:14.093 回答
1

您必须替换此行

@posts = Post.where(:name => params[:name])

category = Category.where(:name => params[:name]).first
@posts = category.posts
于 2013-08-02T12:48:04.477 回答