0

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 #<ActiveRecord::Relation:0x007feae4af0e70>

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.

unlikely_monkey
  • 183
  • 4
  • 15

1 Answers1

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.

HargrimmTheBleak
  • 2,147
  • 1
  • 19
  • 19
  • To your question, actually it wouldn't. It does give me all the tagged tasks regardless of project. I was looking for the tasks as a subset of each project, hence the `Tag.find(1).projects.tasks` attempt. I did just get it working but I think you explained it. My original approach was trying to get results for several different projects at the same time. `p[0].tasks` works to get me the result I'm looking for. Thanks for the help! – unlikely_monkey Jul 23 '12 at 13:57