Tolga
Tolga

Reputation: 1357

RAILS - How to define group in associations

I have two associated tables whose models are as shown below.

Here I would like to fetch all "ilans" which are "created_at OR has an associated record (ilanupdates) during the last 36 hours"

Models:

class Ilan < ApplicationRecord
  has_many :ilanupdates
end

class Ilanupdate < ApplicationRecord
  belongs_to :ilan
end

I have problem defining the controller method which generates an error related to GROUP definition. I will appreciate if you can guide me how to solve this issue.

Controller:

 def index
    @ilans = Ilan.left_outer_joins(:ilanupdates).select("ilans.*, count(ilanupdates.*) as ilanupdate_count, max(ilanupdates.old_price) as highest_price").group(:id)
    @ilans = @ilans.where("ilans.created_at > ? OR (ilanupdates.created_at > ?", (Time.now - 36.hours),(Time.now - 36.hours))
    @ilans = @ilans.order('ilans.ad_date DESC, ilanupdate_count DESC, ilans.price ASC')
 end

ERROR MESSAGE:

ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR:  syntax error at or near "GROUP" LINE 1

Upvotes: 0

Views: 89

Answers (1)

Vivek Singh
Vivek Singh

Reputation: 635

I think its a syntax mistake, It should be:

@ilans = Ilan.left_outer_joins(:ilanupdates).select("ilans.*, count(ilanupdates.*) as ilanupdate_count, max(ilanupdates.old_price) as highest_price").group(:id)
@ilans = @ilans.where("ilans.created_at > ? OR ilanupdates.created_at > ?", (Time.now - 36.hours),(Time.now - 36.hours))
@ilans = @ilans.order('ilans.ad_date DESC, ilanupdate_count DESC, ilans.price ASC')

Upvotes: 1

Related Questions