【问题标题】:Rails - Accessing timestamps from a lookup tableRails - 从查找表中访问时间戳
【发布时间】:2010-08-16 19:09:41
【问题描述】:

我正在尝试从查找表中创建的时间戳中获取值。假设我有成分和食谱,以及一个名为成分_食谱的表,其中包含成分 ID、食谱 ID,然后是时间戳。

如何访问这些时间戳?基本上,我需要知道给定成分何时添加到食谱中。

谢谢!

【问题讨论】:

  • 虽然不是便携式解决方案,但您可以使用 find_by_sqlattr_accessor 提取该信息
  • 感谢您的回复。您能否提供更多信息的链接?谢谢。

标签: ruby-on-rails timestamp


【解决方案1】:

所以你现在有这样的东西吗?

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

通过这种方式,您可以将属性添加到混合物表中,这样您就可以了解它们的添加时间、添加者等...

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 2015-04-20
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多