user2469227
user2469227

Reputation:

Is there a different association that behaves like belongs_to?

I'm new to rails and I'm trying to associate a default song with a theme. The problem is if I give the theme a default_song_id attribute, I can only access the song directly with a call to default_song if I make the theme belong_to the song.

My problem with this is basically just the name of the association. The theme obviously doesn't belong to the song in the hierarchy of my models, and the songs have too many attributes already. It doesn't make sense to give songs a theme_id attribute as the songs are involved in plenty of other relations and it really is just the theme that cares about a particular song, plus one song can be referenced by multiple themes.

So do I have any other options?

Upvotes: 0

Views: 66

Answers (2)

Mel T.
Mel T.

Reputation: 116

It sounds as though the 'has_many :through' association might be what you're looking for. There's a great run-through here: http://guides.rubyonrails.org/association_basics.html.

Essentially, you're going to want to set up an intermediary model to join your Song and Theme models without making one explicitly belong to the other. Say you create an "Assignment" model to handle this, your models would say:

class Song < ActiveRecord::Base
  has_many :assignments
  has_many :themes, through: :assignments
end

class Theme < ActiveRecord::Base
  has_many :assignments
  has_many :songs, through: :assignments
end

class Assignment < ActiveRecord::Base
  belongs_to :song
  belongs_to :theme
end

For each pairing you then have an Assignment with a theme_id and a song_id so you can always query the Assignments table where theme_id/song_id = x to retrieve either associated record. Hopefully this approach is flexible enough to do what you're trying to do.

Upvotes: 1

MrTheWalrus
MrTheWalrus

Reputation: 9700

As concerns using another name for the association definition: No.

Rails is an opinionated framework, by design - convention over configuration. belongs_to is the keyword its designers have chosen for this concept in the DSL of model/association descriptions, and you should try to get used to using it. Try to keep in mind that what you're writing is still code; just because a lot of Ruby/Rails reads like English, that does not mean it is English, and keywords aren't always going to have the same meaning as the English words they look like.

It is theoretically possible to alias belongs_to and the other association macros, but you really shouldn't. It will harm the readability of your code if anyone else ever has to use it.

Upvotes: 0

Related Questions