views:

65

answers:

1

I have a situation where in theory I would need to use a belongs_to_many relationship. I have an Example model and a Sentence model. Each example object has one sentence but these sentences are not necessarily unique. So, for example, I could have two example models that each have one sentence that is the same sentence. I'm not sure how to go about doing this in rails. I tried using has_and_belongs_to_many, but ran into problems. It seems that I only need the belongs_to :many part of that relationship. Ideally it would look something like this, but I know there is no belongs_to :many.

Example has_one :sentence end

Sentence belongs_to_many :examples end

+2  A: 

I think you are confused by the direction your data is being accessed from. Here how your code should look like:

# app/models/example.rb
class Example
  belongs_to :sentence
end

# app/models/sentence.rb
class Sentence
  has_many :examples
end
Eimantas