Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamps on HABTM relationships with ActiveRecord

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?

like image 235
deadkarma Avatar asked Jan 24 '12 21:01

deadkarma


1 Answers

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)
like image 147
Gazler Avatar answered Sep 26 '22 15:09

Gazler