Reputation: 61
I would like to understand the rails conventions around model and table names. For example:
I have the following models:
class Blog < ApplicationRecord
has_many :posts
end
class Post < ApplicationRecord
belongs_to :blog
has_one :metric
end
class Metric < ApplicationRecord
belongs_to :post
end
This generates the following tables:
blogs
posts
metrics
This can be confusing because metrics doesn't contain a namespace in the name (like post_metrics
). Should I instead create a model PostMetric
or perhaps change the name of the table with table_name = 'post_metrics'
? Is there a clear rule here?
Thank you.
Upvotes: 1
Views: 937
Reputation: 101811
PostMetric
is not namespaced. Its just a slightly more descriptive name than just Metric
.
Namespacing is when you nest your models in a module for disambiguation or code organization:
# app/models/blogs/metric.rb
module Blogs
# table name is blogs_metrics
class Metric < ApplicationRecord
end
end
# app/models/posts/metric.rb
module Posts
# table name is posts_metrics
class Metric < ApplicationRecord
end
end
Note that the tables are named plural_plural
- blogs_metrics
. Rails automatically infers that the class is nested when the first "word" is plural.
There are no hard and fast rules when it comes to naming and code organisation. Its up to you as the author to make the most descriptive names possible without being excessively verbose.
Upvotes: 0
Reputation: 577
If you're sure that Metric
should only be related to Post
, then PostMetric
or Posts::Metric
would be good solutions. For Posts::Metric
, you can read more about namespacing ActiveRecord models for organization purposes here.
If you think Metric
could be used more broadly, you could leave it as is, but make the relationship polymorphic so that you can relate Metric
to other models.
Also, it may make better sense to just embed the Metric
data in the post itself by using a jsonb
column (though this would make getting Blog
level metrics more complex):
add_column :posts, :metrics, :jsonb, null: false, default: {}
Lastly, I would avoid leaving it as Metric
and changing the table name. This makes it hard to immediately know that Metric
is in fact post_metrics
.
Upvotes: 2