Vinicius Martinson
Vinicius Martinson

Reputation: 105

Rails ordering through association

I am trying to sort from model Members ascending from Member.board.order

On my controller, institutional_controller.rb I have:

@display = Member.includes(:board).where('is_board = ?', true).order('member.board.order ASC').references(:board)

# board.rb and member.rb

class Board < ActiveRecord::Base
  belongs_to :member
end

class Member < ActiveRecord::Base
  has_one :board
end


# index.html.erb

<% @display.each do |member|  %> [...]

And the error that I am getting is:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "board"
LINE 1: ...= "members"."id" WHERE (is_board = 't')  ORDER BY member.board [...]

Thank you. Any help will be appreciated.

Upvotes: 1

Views: 46

Answers (2)

james2m
james2m

Reputation: 1580

This should do the trick;

@display = Member.joins(:board).where(is_board: true).order('boards.order ASC')

Also you should use;

render 'partial', collection: @display

In your view as it's much more efficient and readable.

Upvotes: 1

Vinicius Martinson
Vinicius Martinson

Reputation: 105

It now works this way:

Member.includes(:board).where('is_board = ?', true).order('boards.order ASC').references(:board)

Upvotes: 2

Related Questions