cman77
cman77

Reputation: 1783

Rails Activerecord querying has_many :through

Need some help with Activerecord Querying in a has_many :through association.

Model:

Job

class Job < ActiveRecord::Base
  has_many :job_metadata, :dependent => :destroy
  has_many :metadata, :through => :job_metadata

Metadatum

class Metadatum < ActiveRecord::Base
  attr_accessible :description, :metadata_type_id
  has_one :metadatum_type
  has_many :job_metadata, :dependent => :destroy
  has_many :jobs, :through => :job_metadata

MetadatumType

class MetadatumType < ActiveRecord::Base
  attr_accessible :description
  has_many :metada

JobMetadatum

class JobMetadatum < ActiveRecord::Base
  attr_accessible :job_id, :metadatum_id
  belongs_to :job
  belongs_to :metadatum

In the console, I can run:

@job.metadata

which returns

=> [#<Metadatum id: 2, description: "Part Time", metadatum_type_id: 1, created_at: "2012-06-23 20:42:14", updated_at: "2012-06-23 20:42:14">] 

But how would I return the metadatum_id on @jobs.metadata which have a metadatum_type_id = 1?

I'm trying this:

@job.metadata.metadatum_id.where('metadata.metadatum_type_id' => 1)

But getting the following error:

NoMethodError:   Metadatum Load (0.3ms)  SELECT "metadata".* FROM 
"metadata" INNER JOIN "job_metadata" ON "metadata"."id" = 
"job_metadata"."metadatum_id" WHERE "job_metadata"."job_id" = 31
undefined method `metadatum_id' 
for #<ActiveRecord::Relation:0x007f7fb3188de8>

Upvotes: 0

Views: 748

Answers (1)

n_i_c_k
n_i_c_k

Reputation: 1534

try this

@the_metadatum_record = @job.metadata.where("metadatum_type_id = 1").first

This searches through the Metadatum records that belong to @job, and looks through those records to find ones that have metadatum_type_id of 1.

Then the id can be accessed like @the_metadatum_record.id

The "first" is added to the end because if your job has more than one metadatum of type 1, the query will return all of them.

Also, I agree with Michael, those are kind of terrible names for tables...

Upvotes: 1

Related Questions