新手问题 mailer 里面不支持 button_to 吗?

litblaky · 2014年04月09日 · 最后由 tsaikoga 回复于 2014年07月03日 · 2002 次阅读

我正在学《Agile Web Development with Rails 4》。按着书做完了发邮件的功能后,接着就添加测试。OrderNotifier 的 shipped 部分的测试过不了,并提示说:

OrderNotifierTest#test_shipped:
ActionView::Template::Error: undefined method `protect_against_forgery?' for #<#<Class:0x8fc1428>:0x94fd978>
    app/views/line_items/_line_item.html.erb:10:in `_app_views_line_items__line_item_html_erb__432531698_80360200'
    app/views/order_notifier/shipped.html.erb:8:in `_app_views_order_notifier_shipped_html_erb___724239349_78115340'
    app/mailers/order_notifier.rb:23:in `shipped'
    test/mailers/order_notifier_test.rb:13:in `block in <class:OrderNotifierTest>'

然后看了一下 _line_item.html.erb 里的第 10 行,发现是一个 button_to 的调用(这是 play time 时加入的)。于是加了个条件,令它在 mailer 渲染时不被调用。最后测试就通过了。

虽然问题解决了,但是很不明白为什么会有这个问题。上网搜了一下发现不止我遇到这问题,但是他们都只讨论折中的解决方案。现在只知道 protect_against_forgery 与 CSRF 有关,然后就没别的头绪了。你们有遇到过这样的问题吗?求解答~

#1 楼 @leozwa 看了一下链接了,这是说要自己写一个 protect_against_forgery? 吗?那为什么在 Controller 里就不用自己写,而在 Mailer 里就要写呢?

我理解是 email 中最好不要带 form email 中的 form 是不带 form token & auth 的 所以没法检查 CSRF

https://rails.lighthouseapp.com/projects/8994/tickets/4700-undefined-method-protect_against_forgery-for-actionviewbase0x10ad1a500

#3 楼 @leozwa 嗯嗯,应该就是这个原因了,Thanks~

需要 登录 后方可回复, 如果你还没有账号请 注册新账号