【问题标题】:Best way to sort through a polymorphic association对多态关联进行排序的最佳方法
【发布时间】:2011-03-26 20:59:46
【问题描述】:

所以 - 具有以下设置:

class Event < ActiveRecord::Base
 has_many :invitations
end

class Invitation < ActiveRecord::Base
  belongs_to :guest, :polymorphic => true
  belongs_to :event
end

class Member > ActiveRecord::Base
  has_many :invitations, :as => :guest

  def full_name
    [first_name, last_name].join(" ")
  end
end

class Visitor > ActiveRecord::Base
  has_many :invitations, :as => :guest

  def full_name
    name
  end
end

最后,我希望能够获取按客人全名排序的活动邀请。我不知道如何 - 谁能帮我解决这个问题?将不胜感激:)

【问题讨论】:

  • 我认为你只能用 Ruby 而不是 sql 因为多态结构可以做到这一点
  • 我猜你是对的!有什么建议吗?

标签: ruby-on-rails sorting polymorphic-associations nested-attributes


【解决方案1】:

至于full_name是一个虚拟属性我可以想象只有ruby解决方案,而不是sql

event = Event.find some event
event.invitations.sort_by(&:full_name) 

【讨论】:

  • order() 是否有类似的选项。例如在索引操作Model...joins()...order()...paginate?还是 order 只占用一个表列?
  • @Sash 在 mysql 中是这样的 Event.order("concat(first_name, last_name) DESC")
  • 太棒了!我还发现.order('COALESCE(column_a, column_b) DESC') 非常有用。
猜你喜欢
  • 2014-07-10
  • 2014-09-16
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 2017-05-23
  • 2021-01-04
  • 2010-12-16
相关资源
最近更新 更多