How to make several has_and_belongs_to_many associations between these two classes?

I have the following setup:

class Publication < ActiveRecord::Base has_and_belongs_to_many :authors, :class_name=>'Person', :join_table => 'authors_publications' has_and_belongs_to_many :editors, :class_name=>'Person', :join_table => 'editors_publications' end class Person < ActiveRecord::Base has_and_belongs_to_many :publications end 

With this setting, I can do something like Publication.first.authors . But if I want to list all the publications in which the person Person.first.publications is involved, this is an error related to the absence of the people_publications connection people_publications . How can i fix this?

Should I switch to separate models for authors and editors? However, this will lead to some redundancy of the database, since a person can be the author of one publication and the editor of another.

+4
source share
2 answers

The other end of your associations should probably be called something like authored_publications and edited_publications with additional read-only publications that returns a union of the two.

Otherwise, you will run into sticky situations if you try to do something like

 person.publications << Publication.new 

because you will never know if a person was an author or editor. Not that this could not be solved otherwise by slightly changing your object model.

There you can also hack ActiveRecord to modify SQL queries or change association behavior, but maybe just saving it is easy?

+3
source

I believe you should have a different association in person model

 class Person < ActiveRecord::Base # I'm assuming you're using this names for your foreign keys has_and_belongs_to_many :author_publications, :foreign_key => :author_id has_and_belongs_to_many :editor_publications, :foreign_key => :editor_id end 
0
source

Source: https://habr.com/ru/post/1310411/


All Articles