18

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.

Huy
  • 10,806
  • 13
  • 55
  • 99
  • Possible duplicate of [Rails 3, ActiveRecord, PostgreSQL - ".uniq" command doesn't work?](https://stackoverflow.com/questions/9758793/rails-3-activerecord-postgresql-uniq-command-doesnt-work) – totymedli Jul 10 '18 at 14:24
  • Your query doesn't follow the standards for Rails 3 and I don't want to give you a poorly constructed solution. The post below answers your question and adheres to Rails 3 conventions. https://stackoverflow.com/questions/9758793/rails-3-activerecord-postgresql-uniq-command-doesnt-work/11476714#11476714 – nslocum Jul 13 '12 at 19:06

1 Answers1

2

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

boulder_ruby
  • 38,457
  • 9
  • 79
  • 100