Search code examples
ruby-on-railsransack

Ransack sort_link for foreign attribute


I have a belongs_to relationship and I'm showing the name of the user is this instance.

But I would like to sort by user name.

<th><%= sort_link @q, :user_id %></th>

How would I go about sorting by the user name rather that user.id?


Solution

  • Your question lacks some necessary details, so I am guessing many things.

    First did you try:

    <th><%= sort_link @q, :user_name %></th>
    

    Or if your user name column name is username:

    <th><%= sort_link @q, :user_username %></th>
    

    Here 'user' before '_' is the name of user table(model).

    You may need to edit the controller to change

    @q = YourModel.search(params[:q])
    

    into

    @q = YourModel.joins(:users).search(params[:q])