我的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
更新
根据Peter在下面的评论,使用rails inbuilt依赖destroy来处理删除相关记录是有意义的。我刚刚尝试将其添加到答案模型中:
has_many:活动,如:: trackable,dependent :: destroy
然而它出错了:
NameError - uninitialized constant Answer::Activity:
PublicActivity表称为活动。我应该为这个has_many协会使用什么名字?
答案 0 :(得分:1)
虽然我认为你仍然应该尝试找出你的显式删除有什么问题,因为它可能表明代码中的其他地方存在问题,我将在这里回答你关于使用{{1 }}
我认为你得到了has_many
,因为关联类的默认名称(即来自单词NameError
的非限定Activity
)不正确。关联的类是activities
。您可以使用PublicActivity::Activity
参数指定它,如http://guides.rubyonrails.org/association_basics.html#options-for-has-many中所述。请注意,您指定了关联的类,并让Rails推断出关联的表名;您没有直接指定表名。