Ruby on rails 通过多态关联进行排序的最佳方法
因此-具有以下设置:Ruby on rails 通过多态关联进行排序的最佳方法,ruby-on-rails,sorting,polymorphic-associations,nested-attributes,Ruby On Rails,Sorting,Polymorphic Associations,Nested Attributes,因此-具有以下设置: 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, :a
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
class事件true
属于:事件
结束
类成员>ActiveRecord::Base
有很多邀请,:as=>:guest
def全名
[名字,姓氏].加入(“”)
结束
结束
类访问者>ActiveRecord::Base
有很多邀请,:as=>:guest
def全名
名称
结束
结束
最后,我希望能够获取由来宾全名订购的活动邀请。我不知道该怎么做-有谁能帮我解决这个问题吗?非常感谢:)因为
全名是一个虚拟属性,我只能想象ruby解决方案,而不是sql
event = Event.find some event
event.invitations.sort_by(&:full_name)
我想你只能用Ruby,不能用sql,因为多态结构我猜你是对的!有什么建议吗?order()
有类似的选项吗。例如,在索引操作模型中…joins()…order()…paginate
?或者order只接受一个表列?@Sash在mysqlEvent.order(“concat(first\u name,last\u name)DESC”)中类似这样的内容
Awesome!我还发现.order('COALESCE(column\u a,column\u b)DESC')
非常有用。