我设置了以下关系:

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


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

最佳答案

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)

09-19 20:50