Often what was supposed to be a belongs_to/has_one relationship is now becoming a has_many relationship. What are the ways to create an intersection table between two tables and enforce a has one association. Is something along these lines possible?
class Book < ActiveRecord::Base
has_one :author, join_table: :author_books
end
class Author < ActiveRecord::Base
has_many :books, join_table: :author_books
end
This way when the association becomes a has and belongs to many at least the database schema does not need to change. In the example above we could then easily switch to once we realise that our software needs to cater for multiple authors on the same book.
class Book < ActiveRecord::Base
has_and_belongs_to_many :authors
end
class Author < ActiveRecord::Base
has_and_belongs_to_many :books
end
Note: No has_one through dumb model I’m aware that we can do something along these lines. I’d like to avoid defining a dumb model that isn’t going to be used other than the purpose of a through. The assumption is the join table will have no other purpose than being an intersection. No validation, no special fields and therefore does not need to be defined as a concept.
class AuthorBook < ActiveRecord::Base
belongs_to :author
belongs_to :book
end
class Book < ActiveRecord::Base
has_one :author_book
has_one :author, through: :author_book
end
class Author < ActiveRecord::Base
has_many :author_books
has_many :books, through: :author_books
end
Question: Can we use some SQL or scopes to define a has_one with the use of a join table that would fit this purpose?