mfisch
mfisch

Reputation: 989

What would the right Rails model association be in this case?

I am trying to learn Rails, and have a question that's confusing me a bit. I have two simple models: Media & MediaType.

Media has things like: title, production_date, cost, etc. It also has a "type" field. This would be a foreign key into the MediaType table. MediaType is simply: id, name, active (t/f).

When I think about this, Media has_one MediaType seems to fit. But I can also see how Media belongs_to MediaType and MediaType has_many Media also fits. From my POV all I really need is for the Media table to store the ID that looks into the MediaTypes table. MediaTypes table shouldn't store anything about Media, so that points me at "has_one".

Which is right and what's the process everyone uses for thinking through these?

Edit: for this example I intend Media to only ever have 1 type.

Upvotes: 1

Views: 78

Answers (2)

the12
the12

Reputation: 2415

My personal recommendation is to scrap media type model and just put it as a field/column for the media model. It only has a total of two relevant fields (name and type), as you wouldn't need id, as that's only really needed to identify media types under the assumption that it is its own separate table. You would just be eliminating unnecessary complexity (can just have one database table vs two). One-to-one relationships only really make sense when the columns for both tables are too large to be stored in one table.

If you absolutely have to include it, then the following should work:

class Media < ActiveRecord::Base
  belongs_to :media_type
end

class MediaType < ActiveRecord::Base
  has_one :media
 end

Note that the model with belongs_to will be the one storing the foreign key of the other model. In this case, because you wanted Media to store MediaTypes, you would need to specify Media has a belongs_to relationship with MediaType. Writing has_one :media for the model MediaType, would complete the one-to-one relationship.

In your migration tables, you will have to include media_type_id in your migrations in the Media model as a column, so that the one-to-one relationship can be stored. Then you'll be able to store which media types go into which media records.

Upvotes: 1

archana
archana

Reputation: 1272

type is not the good name for column, rename it to media_type_id as pointed out by other answer.

# media.rb
class Media < ActiveRecord::Base
  belongs_to :media_type
end

# media_type.rb
class MediaType < ActiveRecord::Base
  has_many :media
end

Upvotes: 0

Related Questions