sumitshining
sumitshining

Reputation: 159

Rails Sorting on a value coming from two columns

I have two tables, A and B. A and B have a foreign key. Both 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

Here the value coming from valueRendered method in A is having values from field value2 of B when value1 is null. I have to sort the table using the valueRendered, i.e., table should be sorted on the basis of values of both value1 and value2. How to proceed?

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.

Some more edit: Actual sample code

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 method is in a helper

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

Upvotes: 0

Views: 503

Answers (1)

Sam Peacey
Sam Peacey

Reputation: 6034

How about something like:

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

Upvotes: 1

Related Questions