Undefined Method on has_many :through-Collection of common programming errors

I have three models:

Class Project < ActiveRecord::Base
  has_many :tasks
  has_many :tags, :through => :tasks
end

Class Tasks < ActiveRecord::Base
  belongs_to :project
  has_and_belongs_to_many :tags
end

Class Tags < ActiveRecord::Base
  has_and_belongs_to_many :tasks
  has_many :projects, :through => :tasks

When I open up console, I can get my Project and Task information as expected:

Tag.find(1).projects
Tag.find(1).tasks

If I want, I can get all the tasks for each project regardless of the tag:

Project.find(1).tasks

For whatever reason, I can’t access tasks if I get projects by tag… something = Tag.find(1).projects something.tasks

…I get the error:

undefined method `tasks' for #

I’ve looked for a couple hours and can’t find anything that corrects this problem. Based on everything I’ve found, it should be working… but it’s not.

I’m using Rails 3.2.3.

  1. Shouldn’t Tag.find(1).tasks give you the same result?

    Anyway, the problem you’re facing is that you’re trying to retrieve an association from a Relation object instead of an instance of your model. Relations can be used to chain query conditions, but you can’t directly reference associations from them. So, to get your example working, you’d need to do

    p = Tag.find(1).projects.includes(:tasks)
    

    Then reference tasks like this: p[0].tasks.

    However I’d just make sure that Tag.find(1).tasks will generate the same SQL and ultimately return the same collection of tasks.

Originally posted 2013-11-10 00:15:58.