我有以下关系设置:
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)