2010-08-16 59 views
1

我试图从查找表中创建的时间戳获取值。假设我有Ingredients和Recipes,还有一个名为ingredients_recipes的表,其中有ingredient_id,recipe_id,然后是时间戳。Rails - 从查找表访问时间戳

我该如何访问这些时间戳?基本上,我需要知道什么时候将某种成分添加到配方中。

谢谢!

+0

虽然不是一个便携式解决方案,您可以使用提取的信息'find_by_sql'和'attr_accessor' – 2010-08-16 19:16:56

+0

感谢您的回应。你能提供更多信息的链接吗?谢谢。 – 2010-08-16 19:19:40

回答

0

所以你现在有这样的事情?

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

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

而你想获得他们添加的日期。轨道的方式是通过使用连接模型。 (见http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)和许多。特别是这条线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.

所以,如果你在哪里建立一个连接模型,你会得到像下面的东西。

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 

这种方式可以将属性添加到混合物表,所以你可以发现,当他们在那里补充说,谁补充他们等等