通过关系表删除一些东西

时间:2011-04-15 10:50:55

标签: ruby-on-rails

我有4个型号。我想删除问题,但现在我不能。不知道为什么。我想,首先我需要删除这个问题的答案,然后删除查询,然后问自己。对。但我怎么做呢?

我的模特:

-respondents_model

class Respondent < ActiveRecord::Base
  has_many :inquiries
  has_many :questions, :through => :inquiries
  has_many :answers,   :through => :inquiries
end

-answer_model

class Answer < ActiveRecord::Base
  belongs_to :inquiry
  belongs_to :question

  validates_uniqueness_of :inquiry_id
end

-question_model

class Question < ActiveRecord::Base
  has_one :answer, :through => :inquiry , :dependent => :destroy
  belongs_to :inquiry , :dependent => :destroy
end

-inquiry_model

class Inquiry < ActiveRecord::Base
  belongs_to :question
  belongs_to :respondent
  has_one    :answer
end

和我的question_controller

  def destroy
    @question.destroy
    head :ok
  end

1 个答案:

答案 0 :(得分:0)

您无需删除答案,因为只要您设置:dependent => :destroy,答案就会被自动删除。所以你只需要打电话:

您还需要指定要销毁的问题:Question.find params[:id]

def destroy
  @question = Question.find params[:id]
  @question.destroy
  head :ok
end