1

我的项目中很少有模型。其中有一些:QualificationCurriculumQualification有孩子(课程)。我想确保当我删除时我会Qualification删除它的所有孩子。这是我的代码:

# Table name: qualifications
#
#  id         :integer         not null, primary key
#  subject_id :integer
#  teacher_id :integer
#  created_at :datetime        not null
#  updated_at :datetime        not null
class Qualification < ActiveRecord::Base
  belongs_to :subject
  belongs_to :teacher

  has_many :curriculums, :dependent => :delete_all
  has_many :school_classes, :through => :curriculums
end

#  id               :integer         not null, primary key
#  school_class_id  :integer
#  qualification_id :integer
#  created_at       :datetime        not null
#  updated_at       :datetime        not null
class Curriculum < ActiveRecord::Base
  belongs_to :school_class
  belongs_to :qualification

  has_one :result

  has_many :timetables
end

如您所见,我尝试:dependent => :delete_all在 Qualification 模型中使用。但它不起作用。为什么?

升级版:

我在编辑时通过取消选中复选框来删除资格:

<div class="control-group"> 
  <%= f.label :subject_ids, "Teacher can teach such subjects in the school", 
              :class => "control-label" %>               

  <div class="controls">
    <table class="table table-bordered table-striped">
      <thead>
        <tr>
          <th>Choose</th>
          <th>Subject</th>
        </tr>
      </thead>
      <tbody>
        <%= hidden_field_tag "teacher[subject_ids][]", nil %>                         <%# We use hidden field because it doesn't submit unchecked fields. So, we pass nil and nothing will be submitted.%>

        <% @subjects.each do |subject| %>                                             
          <tr>                                                                        
            <td>                                                                      
              <%= check_box_tag "teacher[subject_ids][]",                             # [] brackets tells that this is array.
                                subject.id,                                           # Value of checkbox.
                                @teacher.subject_ids.include?(subject.id),            # Here we automatically check checkboxes.
                                id: dom_id( subject ) %>                              <%# Give unique id for each value. 'dom_id' is Rails helper. We will have ids like: 'subject_1', 'subject_2' and etc. %>
            </td>                                                                     
            <td>                                                                      
              <%= label_tag dom_id( subject ), subject.subject_name %>                <%# Put name of subject. %>
            </td>
          </tr>
        <% end %>
      </tbody>
    </table>
  </div>
 </div>

这是更多信息:

class Teacher < ActiveRecord::Base  
  has_many :qualifications
  has_many :subjects, :through => :qualifications
end

class Subject < ActiveRecord::Base
  has_many :qualifications
  has_many :teachers, :through => :qualifications  
end

这是我更新模型时的 SQL 代码:

Started PUT "/teachers/2" for 127.0.0.1 at 2012-06-03 18:34:44 +0400
Processing by TeachersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZJNNV9/TO6k18O1Ar1kpkU+PWbd7btHm9Tc067iMNO4=", "teacher"=>{"teacher_last_name"=>"Last", "teacher_first_name"=>"First", "teacher_middle_name"=>"Middle", "teacher_sex"=>"m", "teacher_birthday"=>"1980-12-01", "teacher_phone_attributes"=>{"teacher_mobile_number"=>"88283686", "teacher_home_number"=>"5112787", "id"=>"2"}, "teacher_education_attributes"=>{"teacher_education_university"=>"Mmm", "teacher_education_year"=>"1970-01-01", "teacher_education_graduation"=>"Graduated", "teacher_education_speciality"=>"Math", "id"=>"2"}, "teacher_category"=>"1st", "subject_ids"=>["", "4", "3", "1"]}, "commit"=>"Update", "id"=>"2"}
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
  Teacher Load (0.4ms)  SELECT "teachers".* FROM "teachers" WHERE "teachers"."id" = $1 LIMIT 1  [["id", "2"]]
   (0.1ms)  BEGIN
  Subject Load (0.5ms)  SELECT "subjects".* FROM "subjects" WHERE "subjects"."id" IN (4, 3, 1)
  Subject Load (0.5ms)  SELECT "subjects".* FROM "subjects" INNER JOIN "qualifications" ON "subjects"."id" = "qualifications"."subject_id" WHERE "qualifications"."teacher_id" = 2
  SQL (0.4ms)  DELETE FROM "qualifications" WHERE "qualifications"."teacher_id" = 2 AND "qualifications"."subject_id" = 2
  TeacherPhone Load (0.4ms)  SELECT "teacher_phones".* FROM "teacher_phones" WHERE "teacher_phones"."teacher_id" = 2 LIMIT 1
  TeacherEducation Load (0.4ms)  SELECT "teacher_educations".* FROM "teacher_educations" WHERE "teacher_educations"."teacher_id" = 2 LIMIT 1
   (24.1ms)  COMMIT
Redirected to http://0.0.0.0:3000/teachers
Completed 302 Found in 57ms (ActiveRecord: 27.2ms)
4

3 回答 3

2

尝试:

:dependent => :destroy 

代替:dependent => :delete_all

于 2012-06-02T16:34:12.393 回答
1

不确定这是否是您正在做的,但我可以使用 :dependent => :delete_all 删除家属

我没有使用删除,而是在我的控制器中使用了销毁。

示例:而不是:Qualification.delete(params[:id])

    Use this:
         Qualification.destroy(params[:id])

希望这可以帮助。=)

于 2012-10-08T04:52:32.363 回答
0

“rails 3 way”说 -

(第 187 页)清除

通过清除外键字段以事务方式从该关联中删除所有记录(请参阅删除)。如果关联配置了 :dependent 选项设置为 :delete_all,则它调用 delete_all。同样,如果 :dependent 选项设置为 :destroy_all,则调用 destroy_all 方法。

delete(*records) 和删除—全部

delete 和 delete_all 方法分别用于切断指定的关联或所有关联。这两种方法都是事务性的。值得注意的是,出于性能原因,调用 delete_all 首先将关联对象的整个集合加载到内存中以获取它们的 ID。然后它执行一个 SQL UPDATE 将所有当前关联对象的外键设置为 nil,从而有效地将它们与其父对象解除关联。由于它将整个关联加载到内存中,因此不建议将此方法用于关联对象的极大集合。

笔记

delete 和 delete_all 方法的名称可能会产生误导。默认情况下,它们不会从数据库中删除任何内容——它们只会通过清除关联记录的外键字段来切断关联。此行为与 :dependent 选项有关,该选项默认为 :nullify。如果关联配置的 :dependent 选项设置为 :delete 或 :destroy,那么关联的记录实际上会从数据库中删除。

:dependent => :destroy 或 :delete

根据选项的值,指定关联所有者记录应该被销毁或从数据库中删除的规则。触发时, :destroy 将调用依赖的回调,而 :delete 不会。

在 has_one / belongs_to 配对中使用此选项可能有意义。但是,您不太可能希望在 has_many / belongs_to 关系上出现这种行为;以这种方式编码似乎没有意义。此外,如果所有者记录在相应的 has_many 关联上设置了其 :dependent 选项,则销毁一个关联记录将产生破坏其所有同级记录的连锁反应。

于 2012-10-08T05:09:44.143 回答