soBinary
soBinary

Reputation: 429

Issues with "has_one" in Rails

I'm trying to do something extremely simple but can't find a solution in RailsGuides.

I have two tables, words and flavors. There's a dictionary's worth of words, and only about 10 flavors. I want each word to have a flavor.

I've tried many combinations of flavor_id and word_id in the migrations, and has_one and belongs_to in the models, but always run into problems. Giving the has_one to the word isn't right because then each flavor could only be associated to one word. Flipping the has_one doesn't help because it prevents me from doing things like word.flavor = Flavor.some_flavor.

Is there a method for handling such scenarios?

Update: I had to drop both tables and recreate them, and David Underwood's solution worked.

Upvotes: 0

Views: 30

Answers (1)

David Underwood
David Underwood

Reputation: 4966

Here are some class definitions that will work:

class Word < ActiveRecord::Base
  belongs_to :flavor
end

class Flavor < ActiveRecord::Base
  has_many :words
end

In your schema, you want the words table to have a flavor_id column. You don't need a foreign key on the flavors table.

The key is that each word is associated with a single flavor, and a single flavor can be associated with many words.

You can now call word.flavor to get the flavor of a word as well as flavor.words to get an array of words with that flavor.

Upvotes: 2

Related Questions