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

前端之家收集整理的这篇文章主要介绍了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)
原文链接:https://www.f2er.com/ruby/273486.html

猜你在找的Ruby相关文章