我正在尝试从查找表中创建的时间戳中获取值。假设我有成分和食谱,以及一个名为ingredients_recipes的表,其中包含ingredient_id,recipe_id,然后是时间戳。
如何访问这些时间戳?基本上,我需要知道何时将某种成分添加到配方中。
谢谢!
答案 0 :(得分:0)
所以你现在有这样的东西?
class ingredient << ActiveRecord::Base
has_and_belongs_to_many :recipes
.....
end
class recipe << ActiveRecord::Base
has_and_belongs_to_many :ingredients
....
end
并且您希望获得添加的日期。 rails的方法是使用连接模型。 (见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
通过这种方式,您可以将属性添加到混合表中,这样您就可以了解添加的位置,添加位置等等...