Reputation: 339
I'm fairly new to rails and I'm having trouble with some Model Relationships.
I have these tables
+--------------+-----------------+------+
| Artists | Artist Features | Tags |
+--------------+-----------------+------+
| ID | ID | ID |
| Name | artist_id | name |
| Address | price | |
| Country | tag_id | |
| Email | | |
+--------------+-----------------+------+
I have relationships between Artists and Artist Features
artists
has_many
artist_features
and artist_features
has_many
tags. I want to, with a query get all Artists, features and tags based on the structure above, artist_id
and tag_id
I've used the below to get the artists
and the corresponding artist_features
but would like to also get the tags too based on the tag_id
@Artists = Artist.all.artist_features
Upvotes: 0
Views: 56
Reputation: 27374
If an artist feature has_many
tags, then you need to change your table columns to match this relationship structure.
A has_many
/belongs_to
relationship always requires that the model with the belongs_to
method call has a foreign key column.
In this case, you want to have a set of tags and allow artist features to reference these tags. We can do this by adding another model between ArtistFeature
and Tag
, called ArtistFeatureTag
, with a table artist_feature_tags
.
Your model structure then would look like this:
Artist: id
, name
, address
, country
, email
class Artist
has_many :artist_features
end
Artist Feature: id
, artist_id
, price
class ArtistFeature
belongs_to :artist
has_many :artist_feature_tags
has_many :tags, through: :artist_feature_tags
end
ArtistFeatureTag: id
, artist_feature_id
, tag_id
class ArtistFeatureTag
belongs_to :artist_feature
belongs_to :tag
end
Tag: id
, artist_feature_id
, name
class Tag
has_many :artist_feature_tags
has_many :artist_features, through: :artist_feature_tags
end
The extra table may seem unintuitive, but it's necessary to store the relationship between artist features and tags, i.e. multiple artist features may reference the same tag, and these references take the form of ArtistFeatureTag
s.
Note that this is basically a has and belongs to many-type relationship, but I've decided to explicitly create a model for the relationship since I think it makes things more clear.
Upvotes: 1