开发者

Problem with deleting row

Hm, First time i see this when i want to delete row: ( I want to delete respondent.email) i got his:

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

Model of users:

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

question model:

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

answer model

  belongs_to :inquiry
  belongs_to :question

inquiry model

  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


Let's start.

First - it is wrong code:

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

Second, you havent got respondent_id in your inquiries table and you should define

has_many :respondents

in your Inquiry model.

Third you can't use this

has_one :answer,   :through => :inquiry

as far as association inquiry is not defined.

So you should

  • add respondent_id to your inquiries table
  • add belongs_to :respondent association to your Inquiry model
  • delete has_one :answer, :through => :inquiry association from Respondent model. Or figure out what is it and add some new association to fix it.

And read some articles about Rails associations.

Your problem is not a bad code. Your problem is that you don't understand what you are doing. You should feel Rails and you should love Rails. God bless you

Also you haven't got question_id in your answers table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜