Programming

협회를 통한 belongs_to

procodes 2020. 7. 1. 22:16
반응형

협회를 통한 belongs_to


다음과 같은 연관성을 고려할 때 Questiona ChoiceChoice모델 에서 연결되어 있음 을 참조해야합니다 . belongs_to :question, through: :answer이 작업을 수행하는 데 사용하려고했습니다 .

class User
  has_many :questions
  has_many :choices
end

class Question
  belongs_to :user
  has_many :answers
  has_one :choice, :through => :answer
end

class Answer
  belongs_to :question
end

class Choice
  belongs_to :user
  belongs_to :answer
  belongs_to :question, :through => :answer

  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
end

나는 얻고있다

초기화되지 않은 상수 User::Choice

내가하려고 할 때 current_user.choices

내가 포함하지 않으면 잘 작동합니다.

belongs_to :question, :through => :answer

그러나 나는 그것을 할 수 있기를 원하기 때문에 그것을 사용하고 싶습니다. validates_uniqueness_of

아마도 간단한 것을 간과하고있을 것입니다. 도움을 주시면 감사하겠습니다.


belongs_to협회는 할 수 없습니다 :through옵션을 선택합니다. 당신은 캐싱 더 낫다 question_idChoice테이블에 고유 인덱스를 추가 (특히 때문에이 validates_uniqueness_of경쟁 조건하는 경향이있다).

편집증 환자라면 Choice답변의 question_id일치 여부 를 확인 하는 사용자 지정 유효성 검사를 추가 하지만 최종 사용자에게 이러한 종류의 불일치를 생성하는 데이터를 제출할 기회가 주어지지 않는 것처럼 들립니다.


다음을 위임 할 수도 있습니다.

class Company < ActiveRecord::Base
  has_many :employees
  has_many :dogs, :through => :employees
end

class Employee < ActiveRescord::Base
  belongs_to :company
  has_many :dogs
end

class Dog < ActiveRecord::Base
  belongs_to :employee

  delegate :company, :to => :employee, :allow_nil => true
end

다음 과 같이 has_one대신 대신 사용 하십시오.belongs_to:though

class Choice
  belongs_to :user
  belongs_to :answer
  has_one :question, :through => :answer
end

관련이 없지만 데이터베이스에서 적절한 고유 제약 조건을 사용하는 대신 validates_uniqueness_of를 사용하는 것이 주저합니다. 루비에서이 작업을 수행하면 경쟁 조건이 있습니다.


내 접근법은 데이터베이스 열을 추가하는 대신 가상 속성을 만드는 것이 었습니다.

class Choice
  belongs_to :user
  belongs_to :answer

  # ------- Helpers -------
  def question
    answer.question
  end

  # extra sugar
  def question_id
    answer.question_id
  end
end

This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer from the db, and then question. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.

There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.


It sounds like what you want is a User who has many Questions.
The Question has many Answers, one of which is the User's Choice.

Is this what you are after?

I would model something like that along these lines:

class User
  has_many :questions
end

class Question
  belongs_to :user
  has_many   :answers
  has_one    :choice, :class_name => "Answer"

  validates_inclusion_of :choice, :in => lambda { answers }
end

class Answer
  belongs_to :question
end

So you cant have the behavior that you want but you can do something that feels like it. You want to be able to do Choice.first.question

what I have done in the past is something like this

class Choice
  belongs_to :user
  belongs_to :answer
  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
  ...
  def question
    answer.question
  end
end

this way the you can now call question on Choice


The has_many :choices creates an association named choices, not choice. Try using current_user.choices instead.

See the ActiveRecord::Associations documentation for information about about the has_many magic.

참고URL : https://stackoverflow.com/questions/4021322/belongs-to-through-associations

반응형