与ActiveRecord的HABTM关系的时间戳

dea*_*rma 16 activerecord ruby-on-rails

我有以下关系设置:

class Article < ActiveRecord::Base
  has_and_belongs_to_many :authors
end

class Author < ActiveRecord::Base
  has_and_belongs_to_many :articles
end
Run Code Online (Sandbox Code Playgroud)

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

Author.first.articles << Article.first
Run Code Online (Sandbox Code Playgroud)

重要的是我要跟踪作者何时与文章相关联.有没有办法可以做到这一点?

Gaz*_*ler 14

导轨指南.

最简单的经验法则是,如果需要将关系模型作为独立实体使用,则应设置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
Run Code Online (Sandbox Code Playgroud)

如果它仍然不能与该结构一起使用,那么使用create来代替使用数组推送.

Author.first.article_authors.create(:article => Article.first)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!创建单独的关系模型是有效的.我不认为存储时间戳足以保证单独的模型. (3认同)