Topic: Trouble with active record

Hello,

I am trying to add some sortability without leaving ActiveRecord.....

I have 3 tables

Employee
Training
Sop

This is my model
class Employee < ActiveRecord::Base
  attr_accessible :first_name,:last_name, :title
  has_many :trainings
  has_many :sops, :through => :trainings
end

class Sop < ActiveRecord::Base
  attr_accessible :effective, :rev, :sop, :title, :trainer
  has_many :trainings
  has_many :employees, :through => :trainings
end

class Training < ActiveRecord::Base
  attr_accessible :employee_id, :info, :sop_id
  has_one :employee
  has_one :sop
  belongs_to :employee
  belongs_to :sop
end

So the training table is used to track what sops an employee
need or has been trained on.

To find all the trainings that an employee has I could do
@employee = Employee.find( params[:id] )
@t = @employee.Trainings

What I show in a table is something like below:
sop                      title                     training status (or info)
@t[0].sop.sop     @t[0].sop.title    @t[0].info
....

How would I efficiently sort @t via the different columns using some order call?


I have an SQL answer below, but then I am thinking moving away from Active record might
bite me later.

SQL:
What I have come up with is

sort_column = "sop"
I could also use "title" or "info" here

sort_direction = "asc"
sql="SELECT Trainings.info,Sops.sop,Sops.title,Sops.id "\
    "FROM Trainings,Sops " \
    "WHERE Trainings.employee_id = #{@employee.id} AND Trainings.sop_id = Sops.id "\
    "GROUP BY Sops.id,Trainings.info,Sops.sop,Sops.title "\
    "ORDER BY #{sort_column} #{sort_direction} "\
    ";"
@t = ActiveRecord::Base.connection.execute(sql)

This works, I can pass in sop or title or info and get the sorted results.

Is there an easy way to do this in ActiveRecord?
Every attempt I have made call
Training.find(XXXXXX)
has failed.

Thanks for taking the time to look at my question
Kevin

Last edited by ktacheny (2013-04-25 14:51:07)

Re: Trouble with active record

The first thing which jumps into the eyes is:

has_one :employee
  has_one :sop
  belongs_to :employee
  belongs_to :sop

in your Training model. You should leave only 'belongs_to' relations.
See more details and examples at Rails guides: http://guides.rubyonrails.org/association_basics.html