views:

16

answers:

1

Hola all,

I'm trying to get the values from timestamps created in a lookup table. Let's say I've got Ingredients and Recipes, and a table called ingredients_recipes, with ingredient_id, recipe_id, and then the timestamps.

How can I get access to those timestamps? Basically, I need to know when a given ingredient was added to a recipe.

Thanks!

A: 

So you currently have something like this?

class ingredient << ActiveRecord::Base
  has_and_belongs_to_many :recipes
  .....
end

class recipe << ActiveRecord::Base
  has_and_belongs_to_many :ingredients
  ....
end

And you want to get the dates they where added. The rails way to do this is by using a join model. (see http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html ) and many to many. particularly this line Choosing which way to build a many-to-many relationship is not always simple. If you need to work with the relationship model as its own entity, use has_many :through. Use has_and_belongs_to_many when working with legacy schemas or when you never work directly with the relationship itself.

So if you where to build a join model you would get something like below.

class ingredient << ActiveRecord::Base
  has_many :mixtures
  has_many :recipes , :through=> :mixtures
  .....
end

class recipe << ActiveRecord::Base
   has_many :mixtures
   has_many :ingredients, :through=> :mixtures
  ....
end

class mixture << ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
  ...
end

This way you can add attributes to the mixtures table, so you can find out when they where added, who added them etc...

Doon