开发者

Simulating a belongs_to_many in rails

开发者 https://www.devze.com 2022-12-29 21:46 出处:网络
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 nece

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消