删除行的问题

时间:2011-04-21 10:38:36

标签: ruby-on-rails

嗯,我第一次看到这个,当我想要删除行:(我想删除respondent.email)我得到了他的:

Mysql::Error: Cannot delete or update a parent row: a foreign key constraint fails (`survey_development`.`inquiries`, CONSTRAINT `inquiries_ibfk_2` FOREIGN KEY (`respondent_id`) REFERENCES `respondents` (`id`)): DELETE FROM `respondents` WHERE `id` = 4

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

respondents_controller

  # DELETE /respondents/1
  def destroy
    @respondent.destroy
    head :ok
  end

respondent_model

class Respondent < ActiveRecord::Base
  has_many :inquiries
  has_many :questions, :through => :inquiries
  has_one :answer,   :through => :inquiry
end

1 个答案:

答案 0 :(得分:0)

让我们开始。

首先 - 这是错误的代码:

class Respondent < ActiveRecord::Base
  has_many :inquiries
  has_many :questions, :through => :inquiries
  has_one :answer,   :through => :inquiry
end

其次,你的respondent_id表中没有inquiries,你应该定义

has_many :respondents

Inquiry模型中。

第三,你不能使用这个

has_one :answer,   :through => :inquiry

至于未定义关联inquiry

所以你应该

  • respondent_id添加到您的inquiries表格
  • belongs_to :respondent关联添加到您的Inquiry模型
  • has_one :answer, :through => :inquiry模型中删除Respondent关联。或弄清楚它是什么,并添加一些新的关联来修复它。

<强> And read some articles about Rails associations

你的问题不是一个糟糕的代码。你的问题是你不明白你在做什么。你应该感觉Rails,你应该喜欢Rails。 上帝保佑你

此外,您的question_id表格中还没有answers