从2个表中获取数据

时间:2011-04-21 07:12:56

标签: ruby-on-rails

我有4个表:问题,答案,用户和查询(所有这些表之间的关系表)

这个my_controller

  def index
    question_id = params[:id].to_i
    question    = Question.find(question_id)
    @answers    = question.answers

    respond_to do |format|
      format.ext_json { render :json => @answers.to_ext_json(:class =>
Answer) }
    end
  end

我在extjs中有网格,当我点击行时,我得到答案 我刚刚选择的问题,COOL。但我需要粘贴此信息电子邮件 人(用户表中的电子邮件存储)。现在我有了这个:

| id | answer |
  1  |   lala
  2  |   lalala2

但我需要这个:

| id | answer |  email
  1  |   lala |  alal@sa.com
  2  |   lal2 |  asasa@was.net

P.S

users (table): id, email 
questions (table): id, text 
inquiries: question_id, user_id 
answers: inquiry_id, text

用户模型:

has_many :inquiries 
has_many :questions, :through => :inquiries 
has_many :answers, :through => :inquiries

问题模型:

has_many :inquiries, :dependent => :destroy 
has_many :answers, :through => :inquiries, :dependent => :destroy 

回答模型

  belongs_to :inquiry
  belongs_to :question

查询模式

  belongs_to  :question
  belongs_to  :users
  has_one    :answer, :dependent => :destroy

1 个答案:

答案 0 :(得分:0)

你需要这样的东西:

在答案模型中

has_one :user, :through => :inquiries