ruby-on-rails – 与ActiveRecord的HABTM关系的时间戳

我有以下关系设置:
class Article < ActiveRecord::Base
  has_and_belongs_to_many :authors
end

class Author < ActiveRecord::Base
  has_and_belongs_to_many :articles
end

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

Author.first.articles << Article.first

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

解决方法

rails guides.

The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model,it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database).

You should use has_many :through if you need validations,callbacks,or extra attributes on the join model.

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)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...