mysql - Rails 对来自两列的值进行排序

标签 mysql ruby-on-rails model-associations

我有两个表,A 和 B。A 和 B 有外键。都是 ActiveRecord。

class A
  has_one :b
  def valueRendered
    b.value1 || b.value2
  end
end

class B
  ( belongs_to :a, :foreign_key => :keyb ) if self.b
end

这里,当 value1 为 null 时,来自 A 中的 valueRendered 方法的值具有 B 的字段 value2 中的值。我必须使用 valueRendered 对表进行排序,即表应根据 value1 和 value2 的值进行排序。如何进行?

Edit: To be more specific, suppose there is one calculated column (a method in rails) which has value from field "value1" but if value1 is null, the value comes from "value2". I want to sort the whole table (not limited to any specific no of records or scope) with respect to this calculated field (method). I am confused how to proceed.

更多编辑:实际示例代码

In the controller,

  sort_fields = ['offer_orders.id','offers.name','offer_orders.created_at',  
  'offer_orders.country', 'offer_orders.ip_address',       
  'fraud_score_daily.adjusted_fraud_probability, fraud_score_daily.fraud_probability',                    
  'players.email','players.account_status',
  nil,
  nil,
  nil, 
  nil 
  ]

  arel = OfferOrder.includes(:offer, :player, :fraud_score_daily).group('fraud_score_daily.offer_order_id').order('dt desc')
  arel = paginate_table_data(arel, :sort_fields => sort_fields)

paginate_table_data 方法位于助手中

def paginate_table_data(arel, opts={})
  opts.assert_keys(:required => [:sort_fields])
  @page_size = page_size
  @current_page = current_page
  arel.paginate(:page => @current_page, :per_page => params[:iDisplayLength]).
  order(order_by(opts[:sort_fields]).join(', '))
end

最佳答案

怎么样:

scope :order_by_value_rendered, joins(:b).order("value1, value2")

关于mysql - Rails 对来自两列的值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15358164/

相关文章:

php - Mysql 我正在合并表。但我不能做过滤排序

ruby-on-rails - 在 EC2 上部署 Cassandra?

search - ElasticSearch 中类型内关联的设计建模

ruby-on-rails - 使用to_json时如何访问 ':has_many :though'连接表数据?

java - 类与 JPA 的关系

PHP 使用 cron 作业每天生成 csv

mysql - 无法删除 MySQL 表列

ruby-on-rails - MongoDB ruby 日期

ruby-on-rails - ActiveModel::Serializer:选择 JSON 编码器

php - 数据未从 PHP 发布到 MySQL 表中。请告诉我我在这里做错了什么