与ActiveRecord的HABTM关系的时间戳

时间:2012-01-24 21:20:28

标签: ruby-on-rails activerecord

我有以下关系设置:

class Article < ActiveRecord::Base
  has_and_belongs_to_many :authors
end

class Author < ActiveRecord::Base
  has_and_belongs_to_many :articles
end

我注意到,虽然连接表articles_authors有时间戳,但在创建新关系时它们不会填充。例如:

Author.first.articles << Article.first

跟踪作者与文章的关联时间非常重要。 有没有办法可以做到这一点?

1 个答案:

答案 0 :(得分:14)

来自rails guides.

  

最简单的经验法则是,如果需要将关系模型作为独立实体使用,则应设置has_many:through关系。如果您不需要对关系模型执行任何操作,则设置has_and_belongs_to_many关系可能更简单(尽管您需要记住在数据库中创建连接表)。

     

如果您需要在连接模型上进行验证,回调或额外属性,则应使用has_many:through。

class Article < ActiveRecord::Base
  has_many :article_authors
  has_many :authors, :through => :article_authors
end

class Author < ActiveRecord::Base
  has_many :article_authors
  has_many :articles, :through => :article_authors
end

class ArticleAuthor < ActiveRecord::Base
  belongs_to :article
  belongs_to :author
end

如果它仍然无法使用该结构,那么使用create。

而不是使用数组推送
Author.first.article_authors.create(:article => Article.first)