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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With