0

我的 AnswersController 中有一个 destroy 方法,当它的可跟踪对象被删除时,它也会销毁 public_activity 记录。

答案控制器活动删除:

 def destroy
    @answer = Answer.find(params[:id])
    if @answer.destroy 
       @activity = PublicActivity::Activity.where(trackable_id: @answer.id, trackable_type: "Answer", owner_id: @answer.user.id).first
       @activity.destroy
       respond_to do |format|
          format.js
       end
    end
 end

我的 answers_spec.rb 测试失败:

Answers deletes an answer
 Failure/Error: click_link "delete-answer"
 NoMethodError:
   undefined method 'destroy' for nil:NilClass
 # ./app/controllers/answers_controller.rb:41:in `destroy'
 # (eval):2:in 'click_link'
 # ./spec/requests/answers_spec.rb:20:in `block (3 levels) in <top (required)>'
 # ./spec/requests/answers_spec.rb:19:in `block (2 levels) in <top (required)>' 

我认为这是因为@activity您可以在 中看到的实例变量AnswersController尚未设置,并且没有要尝试删除的公共活动记录。

有没有办法@activity使用答案凭据创建实例变量以便可以将其删除,或者有一种方法可以删除 destroy 方法以便不删除 public_activity 记录?

answers_spec.rb

//omitted for brevity//

it "deletes an answer" do
    visit root_path
    sign_in_user
    create_and_find_question
    create_answer
    page.should have_selector("div", id: "delete-answer")
    expect {
      click_link "delete-answer"
    }.to change(Answer, :count).by(-1)
  end

answer_helper.rb

module AnswerHelper
  def create_and_find_question
    visit questions_path
    click_link "Ask a Question"
    page.should have_content "Step 1: Upload a Video"
    click_link "Step 2"
    page.should have_content "Step 2: Ask your question"
    fill_in "Title", with: "Ball starting too far left"
    fill_in "Body", with: "my clubface is closed..."
    expect {
      click_button "Save"
    }.to change(Question, :count).by(1) 
    page.should have_content "Question Created"
    page.should have_content "Add your answer"
  end

  def create_answer
    click_link "Add your answer"
    page.should have_selector("div", id: "new_answer")
    fill_in "answer_body", with: "You need to shift your weight better"
    expect {
      click_button "Save Answer"
    }.to change(Answer, :count).by(1) 
    page.should have_content "You need to shift your weight better"
  end
 end

更新

根据下面彼得的评论,使用 rails 内置的依赖销毁来处理删除关联记录是有意义的。我刚刚尝试将其添加到答案模型中:

has_many :activities, as: :trackable,dependent: :destroy

但是它出错了: NameError - uninitialized constant Answer::Activity:

PublicActivity 表称为活动。我应该为这个 has_many 关联使用什么名称?

4

1 回答 1

1

虽然我认为您仍然应该尝试找出显式删除出了什么问题,因为它可能表明您的代码中的其他地方存在问题,但我将在这里回答您关于使用has_many.

我认为您得到了 ,NameError因为关联类的默认名称(即不合格的Activity,派生自单词activities)不正确。关联的类是PublicActivity::Activity。您可以使用class_name参数指定它,如http://guides.rubyonrails.org/association_basics.html#options-for-has-many中所述。请注意,您指定关联的类并让 Rails 推导出关联的表名;您不直接指定表名。

于 2013-07-28T17:24:58.037 回答