Search code examples
ruby-on-railsransack

Ransack sort Nested Assosiation on attribute name


I have a model named Project with this association set up to link employees as contributors:

has_many :project_contributions,  dependent: :destroy
has_many :contributors, through: :project_contributions, source: 'employee'

In my view i have this sort field:

<%= sort_link(@q, :contributors_name) %>

This gives me an error when i click the link, it's complaining that the method does not exist.

I can see that since the association is a has_many association i should "name" the sort link something else, but i have no clue what i should be.

Or does Ransack not support has_many sorting? Also it might be that i use a different name that the original table name (employee).

Update: I have discovered that the bug is related to the fact that i have changed the order function to make null values appear last when sorting. Like i show in this answer: https://stackoverflow.com/a/35529699/900271

Does any one know how i can allow nested column sorting while still ordering null values last?


Solution

  • Ok, so now i found the solution in the linked question/answer (that again linked to the github issue).

    In my controller where i order based on the sort column i need to use attr_name instead of just name when i customise the sort order to handle null values last.

    Like so:

    @result = @q.result.except(:order).order("#{@q.sorts.first.attr_name} #{@q.sorts.first.dir} NULLS LAST")