Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by field in related model with ActiveRecord condition

I am trying to order by a field in a related model in Rails. All of the solutions I have researched have not addressed if the related model is filtered by another parameter?

Item model

class Item < ActiveRecord::Base
  has_many :priorities

Related Model:

class Priority < ActiveRecord::Base
  belongs_to :item

  validates :item_id, presence: true
  validates :company_id, presence: true
  validates :position, presence: true
end

I am retrieving Items using a where clause:

@items = Item.where('company_id = ? and approved = ?', @company.id, true).all

I need to order by the 'Position' column in the related table. The trouble has been that in the Priority model, an item could be listed for multiple companies. So the positions are dependent on which company_id they have. When I display the items, it is for one company, ordered by position within the company. What is the proper way to accomplish this? Any help is appreciated.

PS - I am aware of acts_as_list however found it did not quite suit my setup here, so I am manually handling saving the sorting while still using jquery ui sortable.

like image 946
Drew Avatar asked Jun 28 '13 15:06

Drew


People also ask

What are ActiveRecord methods?

The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

Is ActiveRecord part of rails?

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

What is Ruby ActiveRecord?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 Answers

You could use the includes method to include the build association then order by it. You just make sure you disambiguate the field you are ordering on and there are some things you should read up on here on eager loading. So it could be something like:

@items = Item.includes(:priorities).where('company_id = ? and approved = ?', @company.id, true).order("priorities.position ASC")
like image 164
Jay Truluck Avatar answered Oct 11 '22 03:10

Jay Truluck