PG error for SELECT DISTINCT, ORDER BY expressions must appear in select list when trying to view on Heroku

Huy picture Huy · May 3, 2012 · Viewed 13.6k times · Source

I am getting this follow error after I added more relationships to my project. On localhost, the page displays perfectly fine. However, I get an error when trying to view it on heroku.

ActiveRecord::StatementInvalid (PG::Error: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list

Here is my traveldeal controller:

  def show
    @traveldeal = @commentable = Traveldeal.find(params[:id])
    @comments = Comment.all
    @title = @traveldeal.title
    @eventdeals = Eventdeal.tagged_with(@traveldeal.location_tag_list, :any => true, :order => 'RANDOM()', :limit => 3)
  end

traveldeal/show.html

<% unless @eventdeals.blank? %>

  <h1>Events in the area:</h1>

  <% @eventdeals.each do |eventdeal| %>
    <%= link_to eventdeal do %>
      <!-- content -->
    <% end %>
  <% end %>

<% end %>

Heroku logs

SELECT DISTINCT eventdeals.* FROM "eventdeals" JOIN taggings event_taggings_e9f0e2e ON event_taggings_e9f0e2e.taggable_id = eventdeals.id AND event_taggings_e9f0e2e.taggable_type = 'Eventdeal' WHERE (event_taggings_e9f0e2e.tag_id = 1 OR event_taggings_e9f0e2e.tag_id = 3 OR event_taggings_e9f0e2e.tag_id = 4 OR event_taggings_e9f0e2e.tag_id = 5) ORDER BY RANDOM()):

This code was working so that I only displayed 3 random eventdeals that matched location (through act-as-taggable-on) with a traveldeal.

However, after I added a relationship (related to eventdeals but not traveldeals), I started getting the pg error.

Here are the relationships that was added:

trip.rb

class Trip < ActiveRecord::Base
  has_many :eventdealtrips, :dependent => :destroy
  has_many :eventdeals, :through => :eventdealtrips
end

eventdeal.rb

class Eventdeal < ActiveRecord::Base
  has_many :eventdealtrips
  has_many :trips, :through => :eventdealtrips, :dependent => :destroy
end

eventdealtrip.rb

class Eventdealtrip < ActiveRecord::Base
  belongs_to :eventdeal
  belongs_to :trip
end

Any advice on how I can still get a random array of 3 eventdeals?

Thanks.

Answer

boulder_ruby picture boulder_ruby · May 7, 2014

I had this issue and solved it by running order at the end of my daisy chain.