views:

28

answers:

1

I have called a function from a class to find all the items related to a particular ID in a many to many HABTM relationship.

Procedures -> Tasks with a join table: procedures_tasks

I call the information like @example = Procedure.get_tasks(1,1)

I would like to be able to iterate through the data returned so that I can create an instance of each task_id related to the procedure in question

  def self.get_tasks(model_id, operating_system_id)
    find(:first,  :select => 'tasks.id, procedures.id', :conditions => ["model_id = ? AND operating_system_id = ?", model_id, operating_system_id], :include => [:tasks])
  end

I tried rendering the data as i normally would and then using .each do |f| in the view layer, but i get:

undefined method `each' for #<Procedure:0x2b879be1db30>

Original Question:

I am creating a rails application to track processes we perform. When a new instance of a process is created I want to automatically create rows for all the tasks that will need to be performed. tables:

  • decommissions
  • models
  • operating_systems
  • procedures
  • tasks
  • procedures_tasks
  • host_tasks

procedures -> tasks is many to many through the procedures_tasks join table.

when you start a new decommissioning process you specify a model and OS, the model and OS specify which procedure you follow, each procedure has a list of tasks available in the join table. I am wanting to create a entry in host_tasks for each task relevant to the procedure relevant to the decommission being created.

I've done my head in over this for days, any suggestions?

class Procedure < ActiveRecord::Base
  has_and_belongs_to_many :tasks
 #has_many :tasks, :through => :procedures_tasks
# has_many :procedures_tasks
  belongs_to :model
  belongs_to :operating_system
  validates_presence_of :name
  validates_presence_of :operating_system_id
  validates_presence_of :model_id

  def self.get_tasks(model_id, operating_system_id)
    find(:first,  :select => 'tasks.id, procedures.id', :conditions => ["model_id = ? AND operating_system_id = ?", model_id, operating_system_id], :include => [:tasks])
  end

end

the get_tasks method will retrieve the tasks associated with the procedure, but I don't know how to manipulate the data pulled from the database in rails, I haven't been able to access the attributes of the returned object through the controller because they haven't been rendered yet?

ideally i would like to be able to format this data so that I only have an array of the task_id's which i can then loop through creating new rows in the appropriate table.

A: 

It wasn't looping through because I was using the :first option when finding the data. I changed it to :all which allowed me to .each do |f| etc.

Not the best option, but there will only ever be one option anyway, so it won't cause a problem.

inKit