ruby-on-rails 使用计算字段对Ransack进行排序

yc0p9oo0  于 2023-10-21  发布在  Ruby
关注(0)|答案(1)|浏览(118)

在我的rails应用程序中,我使用ransack在我的表的标题上生成排序。
这适用于我的模型中包含的所有列,但我有一个unit_price列,它与下面的Ingredient模型的方法相匹配,这实际上是一个计算字段。
是否可以使用计算字段对列标题进行排序?
是在数据库中保存unit_price字段的唯一解决方案吗?

def unit_price
  self.price_cents / self.quantity_by_pack
end

我在我的模型中尝试了这一点,但不起作用

ransacker :created_at do
46scxncf

46scxncf1#

是的有可能
首先在模型中定义ransacker和ransackable_attributes

ransacker :unit_price do |parent|
  # Functionality of your method using Arel
  parent.table[:price_cents] / parent.table[:quantity_by_pack]
end

def self.ransackable_attributes(auth_object = nil)
  # You can use something like:
  # attrs = super
  # attrs += ['unit_price']

  # But it will be deprecated so it's better to use such method:
  authorizable_ransackable_attributes
end

在那之后,

search = Ingredient.ransack({})
search.sorts = 'unit_price asc'

search.result
# Return Active Record relation with SQL query:
# SELECT "ingredients".* FROM "ingredients"
# ORDER BY "ingredients"."price_cents" / "ingredients"."quantity_by_pack" ASC

search = Ingredient.ransack({})
search.sorts = 'unit_price desc'

search.result
# Return Active Record relation with SQL query:
# SELECT "ingredients".* FROM "ingredients"
# ORDER BY "ingredients"."price_cents" / "ingredients"."quantity_by_pack" DESC

相关问题