我的 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 关联使用什么名称?