【问题标题】:How to sort rails model by has_many last active field?如何按has_many最后一个活动字段对rails模型进行排序?
【发布时间】:2019-01-15 10:37:20
【问题描述】:

我有两个模型:

Userhas_many Subscription.

我的用户模型有一个名为 active_subscription 的函数。

def active_subscription
  subscriptions.where(active: true).last
end

我希望能够按此活动订阅的type_name 字段对我的用户进行排序。我需要使用活动订阅,因为我的视图中只呈现最后一个活动订阅。

我写了这个:

includes(:subscriptions).order("subscriptions.type_name #{sort_order}")

但是,这没有考虑到有效订阅。

有什么想法吗?

【问题讨论】:

  • 你能发布你的用户模型吗?当你说用户有_many订阅;我希望你在User 模型中拥有这样的东西:has_many :subscriptions。另外,您说您没有获得活跃的订阅者;你有潜艇吗?你没有使用你在模型中定义的函数。

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

使用范围可能会有所帮助,以下是您问题的示例

class Subscription < ApplicationRecord

  scope :active_subscription, lambda { where('active = ?',true)}
  scope :type_name_order,     lambda { |q| order("type_name :q", q: "#{q}") }

end

User.subscriptions.active_subscription.type_name_order('DESC').last

@users = Subscription.joins(:user).active_subscription.type_name_order('DESC').select('users.username','subscriptions.*')

@users.first.username # you will get first username

# you can also combine with last 

@users = Subscription.joins(:user).active_subscription.type_name_order('DESC').select('users.*','subscriptions.*').last(10)

# in my above example i'm using * to select all column of table users
# for example your table users has gender column you can use

puts @users.first.gender 

# if table users and subscriptions have same column name for example subscriptions.active and users.active then you should use alias 'AS' in select

【讨论】:

  • 但这会返回订阅。我需要返回一个有序的用户对象列表,按他们的active_subscription.type_name 排序
  • 我只是添加了一个信息,请看我上面的回答
猜你喜欢
  • 2016-06-04
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 2018-01-19
相关资源
最近更新 更多