0

I am new to rails and am having troubles figuring out some things with ActiveRecord.

Right now, I have three models:

class Project < ActiveRecord::Base
    attr_accessible :name
    has_and_belongs_to_many :tags
    has_many :tasks
end

class Task < ActiveRecord::Base
    attr_accessible :todo
    has_and_belongs_to_many :tags
    has_many :tasks
end

class Tag < ActiveRecord::Base
    attr_accesible :description
    has_and_belongs_to_many :projects
    has_and_belongs_to_many :tasks
end

I am trying to create a hash that returns tasks that belong to specific tags so that:

Project_Tasks = { 1 => { project.name, "tasks" => { "task 1", "task 2", "task 3" } 
                  2 => { project.name, "tasks" => { "task 1", "task 2", "task 3" } }

I am not sure quite how to go about creating this. My first inclination is to create a method inside one of the classes (I have gone back and forth on which one... right now, I think it is best served under "tag") that loops through the projects that match the given tag, queries for tasks that match both and append them to the array.

To date, this hasn't worked. I'm completely stumped.

Any thoughts on how I can accomplish this? Is a method the appropriate way to go or is there a trick inside ActiveRecord to create a query that would get me at least close to this?

unlikely_monkey
  • 183
  • 4
  • 15

1 Answers1

0

I have tried to fix your model definitions.

class Project < ActiveRecord::Base
    attr_accessible :name
    has_and_belongs_to_many :tags
    has_many :tasks
end

class Task < ActiveRecord::Base
    attr_accessible :todo
    has_and_belongs_to_many :tags
    belongs_to :project
end

class Tag < ActiveRecord::Base
    attr_accesible :description
    has_and_belongs_to_many :projects
    has_and_belongs_to_many :tasks
end

Now you should be able to access your data(in controller) for a specific project as follows:

@project = Project.find_by_id(1)  # Loaded a project
@tasks = @project.tasks  # all task for this project in an array

To display it in the view:

<%= @project.name %><br />
<% @tasks.each do |task| %>
  <%= task.todo %><br />
<% end %>

I hope this helps

Anil
  • 3,899
  • 1
  • 20
  • 28