加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:29:21 所属栏目:百科 来源:网络整理
导读:我有以下关系设置: class Article ActiveRecord::Base has_and_belongs_to_many :authorsendclass Author ActiveRecord::Base has_and_belongs_to_many :articlesend 我注意到,虽然连接表article_authors具有时间戳,但是在创建新关系时不会填充.例如: Auth
我有以下关系设置:
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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读