Reputation: 63637
A "User" has many "datasets". A "dataset" has many "graphs". How should this be modeled using Rails Associations? Is anything wrong with this setup?
Basically a user can upload many datasets. For each dataset, a user can create several graphs from it. I will need to "get all graphs for a user" and "get all graphs for a dataset".
Models
class User < ActiveRecord::Base
has_many :datasets
has_many :graphs, through: :datasets
end
class Dataset < ActiveRecord::Base
belongs_to :user
has_many :graphs
end
class Graph < ActiveRecord::Base
belongs_to :dataset
belongs_to :user # Do I need this line? Or is it implicit since it belongs to dataset?
end
Tables
Users
id, email
Datasets
id, user_id, name
Graphs
id, dataset_id, type # Do I need "user_id" in here also?
Upvotes: 0
Views: 59
Reputation: 25029
It looks OK apart from the Graph belonging to User part. If Rails supported belongs_to :through, it could be used here, but as it is, having the user_id on the Graph table is not necessary - a Graph's user can simply be retrieved through the Dataset.
Upvotes: 0