ascherman
ascherman

Reputation: 1832

Ransack issue: default sort

I have the next two models:

class Game
  belongs_to :tournament, inverse_of: :games

  validates_presence_of :name
end

class Tournament
  has_many :games, dependent: :destroy

  validates_numericality_of :number
end

So, I have a list of games that shows their tournament's number, and I want as a default to order the list by the tournament's number.

In my controller I have something like this:

@q = Game.search(params[:q])
@q.sorts = 'tournaments_number' if q.sorts.blank?
@q = @q.result(distinct: true).page(params[:page])

The problem is it is not ordering the list by the number. Take a look at the query

    @q = Game.search(params[:q])
    @q.sorts = 'tournaments_number' if q.sorts.blank?
    puts @q.result.to_sql # => SELECT * FROM games
    @q = @q.result(distinct: true).page(params[:page])

But if I order by a field of games, it works great:

    @q = Game.search(params[:q])
    @q.sorts = 'name' if q.sorts.blank?
    puts @q.result.to_sql # => SELECT * FROM games ORDER BY name
    @q = @q.result(distinct: true).page(params[:page])

Do you know what am I doing wrong? How can I be able to sort by the associated attribute?

EDIT:

I've found out that if I do the next, the order works:

    @q = Game.includes(:tournament).order('tournaments.number').search(params[:q])
    puts @q.result.to_sql # => SELECT * FROM games INNER JOIN tournaments ON games.tournament_id = tournaments.id ORDER BY tournaments.number
    @q = @q.result(distinct: true).page(params[:page])

The problem is that, although I can add some conditional, I need to make it work with ransack, given that I use a sort_link in other place, and it is not working.

<%= sort_link(@q, 'tournaments.number') %>

Upvotes: 1

Views: 1044

Answers (2)

Phil R
Phil R

Reputation: 330

shouldn't it be if @q.sorts.blank?

Upvotes: 0

oreoluwa
oreoluwa

Reputation: 5623

What happens when you do this:

@q = Game.search(params[:q])
@q.sorts = 'tournaments.number' if q.sorts.blank?
@q = @q.result(distinct: true).page(params[:page])

Upvotes: 0

Related Questions