我在我的rails应用程序中使用ActiveAdmin。 一切都很好,但现在我正在尝试创建一个范围,该范围将显示没有标签的书籍。
我已经在我的 Book 模型中创建了一个方法来帮助我做到这一点,但我无法在我的 ActiveAdmin 范围内使用它。
I keep getting
undefined method `book_tags?'
如何创建仅显示没有标签的图书的范围?
型
class Book < ActiveRecord::Base
has_many :book_mappings, dependent: :destroy
has_many :tags, through: :book_mappings
###Find books without a tag
def book_tags?
tags.any?
end
end
class BookMapping < ActiveRecord::Base
belongs_to :book
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :book_mappings, dependent: :destroy
has_many :books, through: :book_mappings
end
活动管理员
ActiveAdmin.register Book do
###Scope to shows all Books
scope :all, :default => true
###book_tags? does now work, I keep getting undefined method `book_tags?'
scope :books_without_tags do |book|
book.book_tags?
end
end
它是未定义的,因为作用域是类级别的。book
论点实际上是一个ActiveRecord::Relation
。您可以在块中对其进行优化。您可以使用作用域甚至类方法。
你可以做一些事情:
class Book < AR::Base
scope :without_tags, -> { where.not(id: BookMapping.distinct.pluck(:book_id)) }
end
ActiveAdmin.register Book do
scope :all, default: true
scope :without_tags
end