与ActiveRecord的HABTM关系时间戳 [英] Timestamps on HABTM relationships with ActiveRecord

查看:100
本文介绍了与ActiveRecord的HABTM关系时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下关系设置:

 类文章<的ActiveRecord :: Base的
  has_and_belongs_to_many:作者
结束

一流的作者和LT;的ActiveRecord :: Base的
  has_and_belongs_to_many:文章
结束
 

我注意到,虽然连接表 articles_authors 有时间戳,他们不创造一个新的关系时填充。例如:

  Author.first.articles<< Article.first
 

重要的是,我跟踪当一个作家与项目关联的。 有没有一种方法,我可以做到这一点?

解决方案

在<一个href="http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many">rails指南。

  

经验最简单的规则是,你应该建立一个的has_many:通过关系,如果你需要的关系模型作为一个独立的实体工作。如果你不需要与关系模型做任何事情,它可能是简单的建立一个has_and_belongs_to_many关系(虽然你需要记住在数据库中创建的连接表)。

     

您应该使用的has_many:通过,如果你需要的连接模型验证,回调,或额外的属性。

 类文章&LT;的ActiveRecord :: Base的
  的has_many:article_authors
  的has_many:作者,:通过=&GT; :article_authors
结束

一流的作者和LT;的ActiveRecord :: Base的
  的has_many:article_authors
  的has_many:文章:通过=&GT; :article_authors
结束

类ArticleAuthor&LT;的ActiveRecord :: Base的
  belongs_to的:文章
  belongs_to的:作者
结束
 

如果仍不能与结构的工作,然后,而不是使用数组推,用创建。

  Author.first.article_authors.create(:文章=&GT; Article.first)
 

I have the following relationships setup:

class Article < ActiveRecord::Base
  has_and_belongs_to_many :authors
end

class Author < ActiveRecord::Base
  has_and_belongs_to_many :articles
end

I noticed that, although the join table articles_authors has timestamps, they do not populate when creating a new relationship. For example:

Author.first.articles << Article.first

It's important that I keep track of when an author is associated with an article. Is there a way that I can do this?

解决方案

From the 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

If it still doesn't work with that structure, then instead of using an array push, use a create.

Author.first.article_authors.create(:article => Article.first)

这篇关于与ActiveRecord的HABTM关系时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆