Paul Nelligan
Paul Nelligan

Reputation: 2005

handling order with has_many through relationship

I have two models: project and task (for example) with a join model: project_task enabling a has_many through relationship so that tasks may be shared across projects.

I have specified position as an attribute of the project_task model. Now I want to be able to access tasks by their position in the project_tasks table via a given project.

i.e. project.tasks (ordered by the position listed for each task in the project_tasks table).

Is this possible?

Upvotes: 9

Views: 5427

Answers (3)

Adam Foldvari
Adam Foldvari

Reputation: 71

This is what works for me in Rails 5.x :

has_many :project_tasks
has_many :tasks, -> { order('project_tasks.position') }, through: :project_tasks

Upvotes: 1

Hitesh
Hitesh

Reputation: 825

class Task < AR::Base
   belongs_to :project
   has_one :project_tasks,:through=>:project_tasks
end

class Project < AR::Base 
  has_many :project_tasks
  has_many :tasks ,:through=>:project_tasks,:order => 'project_tasks.position'
end

class ProjectTask < AR::Base
  belongs_to :task
  belongs_to :project
end

Upvotes: 2

Dmitry Polushkin
Dmitry Polushkin

Reputation: 3403

I think something like that can help you:

has_many :project_tasks
has_many :tasks, :through => :project_tasks, :order => 'project_tasks.position'

Upvotes: 18

Related Questions