如何在Ruby on Rails中显示特定类别的帖子

时间:2013-02-09 02:04:44

标签: ruby-on-rails categories

我有一个简单的博客网站,我正在尝试从特定类别中检索帖子。我已将模型设置如下。

class Post < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, through: :categorizations

    attr_accessible :author, :description, :title, :photo, :category_ids

    scope :breaking, lambda { |category_ids|
        joins(:categorizations).where('categorizations.category_id' => category_ids)
    }
end


class Category < ActiveRecord::Base
    attr_accessible :name
    has_many :categorizations
    has_many :posts, :through => :categorizations
end

class Categorization < ActiveRecord::Base

    attr_accessible :category_id, :position, :post_id

    belongs_to :post
    belongs_to :category
end

我在帖子模型中写了一个名为 break 的范围,我不知道如何在视图中渲染它。而且,为了检索特定类别下的帖子,控制器会是什么样子并且我的范围是否会被打破?

1 个答案:

答案 0 :(得分:1)

将范围声明更改为:

scope :breaking, lambda { |category_ids|
    joins(:categorizations).where('categorizations.category_id = ?', category_ids)
}

scope :breaking, lambda { |category_ids|
    joins(:categorizations).where(categorizations: { category_id: category_ids })
}

我更喜欢类方法,而不是在范围上使用lambdas,因为对我来说,它们看起来更具可读性。此外,添加默认值也更容易。

def self.breaking(category_ids)
    joins(:categorizations).where(categorizations: { category_id: category_ids })
end