Topic: has many through relationship question

I have a 'has many through' relationship in my models. I am trying to access objects from either side of this relationship, with mixed results.Here are my models:

class Material < ActiveRecord::Base
  attr_accessible :description, :number
  has_many :parts
  has_many :work_tickets, :through => :parts
  
  validates :number, :presence => {:message => "must be a material part number"}
  validates :description, :presence => {:message => "must be a description"}
end

class Part < ActiveRecord::Base
  belongs_to :material
  attr_accessible :description, :number, :yield, :material_id
  has_many :work_tickets
  has_many :operations, :dependent => :destroy
  
  validates :number, :presence => {:message => "must be a part number"}
  validates :description, :presence => {:message => "must be a description"}
  validates :material_id, :presence => {:message => "must be a material part number"}
end

class WorkTicket < ActiveRecord::Base
  belongs_to :part
  belongs_to :material
  attr_accessible :number, :yield, :opened, :closed, :part_id
  has_many :works, :dependent => :destroy
  
  validates :number, :presence => { :message => "must be a valid work ticket number" }
  validates :opened, :presence => { :message => "must be a valid date/time" }
  validates :closed, :presence => {:message => "must be a valid date/time"}
  validates :part_id, :presence => {:message => "must be a part"}
  validate :opened_must_be_before_closed_time
  
  def opened_must_be_before_closed_time
    errors.add(:opened, " date must be on or before closed date") unless
       self.opened <= self.closed
  end

end

I can access the work_tickets from the material with:

@work_tickets = @material.work_tickets

But, cannot access material from work_ticket:

<%= work_ticket.material.number %>

Forcing me to use:

<%= work_ticket.part.material.number %>

Am I expecting the wrong behaviour, or am I using the wrong relationship pattern?

Last edited by flaps_2000 (2012-08-02 15:56:25)