简体   繁体   English

Rails has_one通过关系

[英]Rails has_one through relationship

I have three tables: question, question_choices and response. 我有三个表:问题,问题选择和答复。

Question

  • ID ID
  • Name 名称
  • Tag 标签

Question_Choice Question_Choice

  • ID ID
  • Question_id Question_id
  • Label 标签
  • Value

Response 响应

  • ID ID
  • User_id 用户身份
  • Question_id Question_id
  • Value

Given a response, I want to see the question tag and the question_choice label for that. 给出响应后,我想查看问题标签和问题标签。 Getting either response or choice to relate to question are no problem, but getting response to relate to choice is proving challenging because I need to say "value=value". 使响应或选择与问题相关都没有问题,但是使响应与选择相关就证明具有挑战性,因为我需要说“值=值”。 I have tried setting up a :has_one, :through => :question relationship but i'm not sure how to express the "value=value" stuff. 我试图建立一个:has_one, :through => :question关系,但是我不确定如何表达“ value = value”的东西。 Do I just need to use raw sql? 我是否只需要使用原始sql?

I assume that you don't want to change the table structure (which would be the easiest solution). 我假设您不想更改表结构(这是最简单的解决方案)。 This is the solution for your current table structure: 这是您当前表结构的解决方案:

app/models/question.rb app / models / question.rb

class Question < ActiveRecord::Base
  has_many :question_choices
end

app/models/question_choice.rb app / models / question_choice.rb

class QuestionChoice < ActiveRecord::Base
  belongs_to :question
end

app/models/response.rb app / models / response.rb

class Response < ActiveRecord::Base
  belongs_to :question
  belongs_to :question_choice, :primary_key => 'value', :foreign_key => 'value', :conditions => proc { "question_id = #{self.question_id}" }
end

Response.first.question_choice will give you the question_choice of the first response . Response.first.question_choice将为您提供第一个responsequestion_choice选择。

I'm guessing questions have many question choices, and that responses have a single 'selected' question choice. 我猜问题有很多问题选择,而答案只有一个“选定的”问题选择。 To model this you would need a direct association between the response and question choice as well, eg 要对此建模,您还需要在答案和问题选择之间建立直接关联,例如

class Question < ActiveRecord::Base
  has_many :question_choices
end

class QuestionChoice < ActiveRecord::Base
  belongs_to :question
end

class Response < ActiveRecord::Base
  belongs_to :user
  belongs_to :question
  belongs_to :question_choice
end

This means that you would need to add a question_choice_id column to your responses table. 这意味着您需要在您的responses表中添加一个question_choice_id列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM