Many-to-Many: Simple vs Rich in Rails - ruby-on-rails

I have a question about these two relationships as I think I'm overthinking it and have confused myself quite a bit.
So they both involve a new table that sits in between the two tables you want to join.
A simple M2M gets the foreign keys from the other two tables (so example would be "blog_posts_categories" table would get the blog_post_id and the category_id foreign keys). Then for the associations, the blog_post and category models would have has_and_belongs_to_many associations with each other but the joined table gets no model.
for a rich M2M, a third joined table is created. This table gets the foreign key from the other two tables, and those two tables get the foreign key of the joined table. Then for the rails association, the joined DOES get a model, and it belongs_to the other two corresponding models. And those two models has_many of the joined table model
Am I anywhere near close to being right? I think my issue is that I keep conflating the table with the model or at least for the simple many-to-many since I keep expecting there should be a model to go along with the table.
Thanks for any direction that can be given.

Your conceptual understanding of the two are almost there. Rather than thinking of them as simple vs. rich, I prefer to think of them as implicit vs. explicit.
Take for example, two models, Book and Author.
With a has_and_belongs_to_many, Rails will implicitly create a join table between your two models. I.e. books_authors.
You can also explicitly create the join table, say, Authorship, that belongs_to both. (Book and Author will then have has_many :authorships.)
In both cases, your domain model will look the same:
Book (1)--(n) Authorship (n)--(1) Author
Now, here is the opninionated part. I prefer to use the explicit approach, as this is easier to grasp, conceptually, and makes it easier to add additional fields to your join table. Say that for example you want the Authorship to be ordered, you can easily add an order column to your Authorship model and use that accordingly.

A third relationship table is suitable for many-to-many relations. You can do something like this:
class BlogPost < ActiveRecord::Base
has_many :blog_post_categories
has_many :categories, through: :blog_post_categories
end
class Category < ActiveRecord::Base
has_many :blog_post_categories
has_many :blog_posts, through: :blog_post_categories
end
class BlogPostCategory < ActiveRecord::Base
belongs_to :blog_post
belongs_to :category
end
The third model is very simple and its overhead is basically negligible. Also it is flexible and extensive if you want to attach more information to that relationship (for example, priority or timestamp). I personally prefer having a standalone table for relationships rather than a few more columns in the blog_posts table.
Here is a relevant blog post: Why You Don’t Need Has_and_belongs_to_many Relationships.
Perhaps you can explain the tradeoffs you're considering here?

Related

How could I best structure these similar models?

I have n models that represent orders, e.g. EbayOrder and AmazonOrder. Each order model has slightly different fields but they all represent the same basic thing, an order.
The problem is that I frequently need to query all my orders to display them in views, add up fees and sales totals, and perform other analyses on them. It's tricky to do this when the models are separate entities.
Here are some options I've considered:
STI
The STI table would likely be dozens of columns wide.
Keeping separate models but generating a replica Order model with normalized data
This would be a slave 'generic' model that would be a one-to-one duplicate of each type of order, but have more normalized cleaner data. I don't like this option because of the data duplication required.
Normalize all order types into a single Order model
Would be ideal if the data were similar enough, but they're pretty different among order types.
Another option would be to use Polymorphic associations:
class Order < ApplicationRecord
belongs_to :specific, polymorphic: true, dependent: :destroy
end
class EbayOrder < ApplicationRecord
has_one :order, as: :specific
end
class AmazonOrder < ApplicationRecord
has_one :order, as: :specific
end
In Order model you can keep shared attributes, but for custom attributes you can use separate model. Anyway this approach makes querying a database more complex.
Also if you use Postgres then you can review another approach: keep all orders in one table but create JSON column for custom attributes.

How do I add items to join tables in Rails? Do they get their own models?

I have two models: Reader and Magazine. I obviously want to have a join table, readers_magazines, to represent which magazines each reader is subscribed to.
So I create my Reader model (with fields like name, address and age) and my Magazine model (with fields like Title and Active?). In each model I write has_and_belongs_to_many of the other.
Then I write a migration, CreateReadersMagazinesJoin, and write:
create_join_table :readers, :magazines do |t|
t.index 'reader_id'
t.index 'magazine_id'
end
And migrate the database. All good.
My question is... what now? Do I create a model for the join table? That seems wrong, and yet I do need some model validations (I don't want to represent the same User-Subscription combo twice). So do I write a model for it and manually specify the database table to use?
What is the correct procedure in this situation?
From the rails guides:
A has_and_belongs_to_many association creates a direct many-to-many
connection with another model, with no intervening model.
That means that using a has_and_belongs_to_many association might be easier for you to setup (because there is no middle model) but you don't have any kind of control over the join table, validations, etc. HABTM are normally considered harmful and you would want to use a has_many :through relationship instead, that is the same but having a model to represent the join table, so you have control over everything.
More information here.
Do I create a model for the join table? That seems wrong, and yet I do need some model validations.
If you don't want to add an additional fields to the join table, you don't really need to create the model for it.
And in most cases the validation that are required by yours, can be applied to one or both the tables.
I don't want to represent the same User-Subscription combo twice.
What do you mean twice, I havent seen the cases for that, however since the User-Subscription is something external the for the join table, you can explain more crear.
Where you have the choice between a habtm relationship or separate model, I would consider whether you need a rich amount of data in the join. In the present case, I think you do need extra data in the join. For example, a subscription would have a start date and an end date. It may also have a billing date and billing amount. You would not normally populate this information in a join table but rather in a stand alone model.
I would call the join table subscriptions and thus create a model Subscription. Then you can do it like this:
class Reader < ActiveRecord::Base
has_many :subscriptions
has_many :magazines, through: :subscriptions
end
class Subscription < ActiveRecord::Base
beongs_to :reader
belongs_to :magazine
end
class Magazine < ActiveRecord::Base
has_many :subscriptions
has_many :readers, through: :subscriptions
end

Rails: mostly has_one / sometimes has_many relationship

This is probably a newbie question, but I cannot figure out the best solution.
I have a Color model and a Cover model.
Most of the time, a cover has_one :color. Maybe one out of one hundred cases, the cover has_many :colors.
Do I have to implement a has_many :through association between the two models? It seems redundant. What's the best practice to define such a relationship?
I think you should cover the general case, when Cover has_many :colors. So this is a many-to-many relationship. In this case, you will have 2 options:
Use join table, if you just need to store cover_id and color_id in the join table, so you will use has_and_belongs_to_many to define your association. With this option, You will have to create join table.
Use join model, if you need to store not only cover_id and color_id, but also other attributes, and you need to do some calculation, so you have to use has_many :through to define your association. With this option, You will have to create new model.
Cover has_many :colors would be best way, even if there is only one single case that requires it.

Model Associations in Rails - many-to-many for multiple models

I'm trying to understand and implement Active Record Associations in Rails and am having some trouble understanding how to put together the specific relationships I need.
I have a Recipe model and an Ingredients model. Many Ingredients will belong to a single Recipe and therefore, a Recipe will have many Ingredients. I am having trouble grasping how this is handled through MySQL and how to implement these relationships in the models correctly. Here is the (relatively sparse) code I have, so far:
models/recipe.rb
class Recipe < ActiveRecord::Base
has_many :ingredients
end
models/ingredient.rb
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :recipes
end
However, I'm fairly certain the association line in ingredient.rb is incorrect.
How would I correctly implement these relationships?
Your Recipe model should have a has_and_belongs_to_many relationship with the ingredients instead of has_many. This allows a single recipe to have many ingredients (i.e. you can do #recipe.ingredients), while a single ingredient can be in many recipes (#ingredient.recipes).
It does seem kind of weird when first starting out, but once you've grokked how Rails relationships work, it becomes intuitive. You're on the right track.
A has_many relationship implements a one to many mapping while has_and_belongs_to_many implements a many to many mapping. So a has_many is paired with a belongs_to while has_and_belongs_to_many are paired together.
The relationship between Recipe and Ingredients will be a many to many one if you also want to find out relations like which recipes a particular ingredient is being used in.
To implement a has_and_belongs_to_many in a mysql db you will have to create a third join table that maps all the links between the two tables.
You can look at this stackoverflow question to get a better idea of the format of the join table.

ActiveRecord two way foreign key.

I'm using some open gov data in MYSQL which I've imported into my rails App.
I've extended the database with some of my own tables, and use the rails provided column ids in my tables.
However, the tables of the original database are linked through a unique 'ndb' id.
I thought that by cross-referencing two :foreign_key=>'ndb' between the models I would get the tables linked properly, but through :foreign_key, it appears to be linking the id from one table to the ndb column of another.
My models look like this
class Food < ActiveRecord::Base
has_many :weights, :foreign_key=>'ndb'
has_many :food_names
end
class Weight < ActiveRecord::Base
belongs_to :food, :foreign_key=>'ndb'
Is there a way to specify that the 'ndb' column is the link between the food and weights table, and not the food_id to ndb?
Have you tried set_primary_key 'ndb' in your AR classes?
set_primary_key docs.
What I've done as a possibly temporary solution, is to used the :finder_sql to link the tables together.
My Food model now has:
class Food < ActiveRecord::Base
has_many :weights, :finder_sql =>'Select weights.* FROM weights LEFT JOIN foods ON foods.ndb=weights.ndb WHERE foods.id=#{id}'
I'm not sure if this is the best solution or not, but it seems to be working.

Resources