-1

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

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

我在 post 模型中写了一个 scope,叫做breaks,我不知道如何在视图中渲染它。还有控制器会是什么样子,为了检索特定类别下的帖子,我的范围是否被打破?

4

1 回答 1

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 })
}

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

def self.breaking(category_ids)
    joins(:categorizations).where(categorizations: { category_id: category_ids })
end
于 2013-02-09T03:03:45.417 回答