嵌套形式的未定义方法`remember_me'

时间:2015-10-28 07:29:17

标签: ruby-on-rails ruby ruby-on-rails-3

我正在关注Michael Hartl的教程,但是当我运行bundle exec rake test时,我收到了这个错误:

<div id="error"><?php echo $error; ?></div><br />

<style>
#error {
font-size:
background-color:
opacity:
color:
padding:
}
</style>

这是new.html.erb文件:

1) Error:
UsersControllerTest#test_should_get_new:
ActionView::Template::Error: undefined method `remember_me' for #<User:0x000000058544b8>
    app/views/users/new.html.erb:25:in `block (2 levels) in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:24:in `block in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:6:in `_app_views_users_new_html_erb__1810619291483938060_46219160'
    test/controllers/users_controller_test.rb:6:in `block in <class:UsersControllerTest>'


  2) Error:
UsersSignupTest#test_invalid_signup_information:
ActionView::Template::Error: undefined method `remember_me' for #<User:0x00000006acef08>
    app/views/users/new.html.erb:25:in `block (2 levels) in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:24:in `block in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:6:in `_app_views_users_new_html_erb__1810619291483938060_46219160'
    test/integration/users_signup_test.rb:6:in `block in <class:UsersSignupTest>'


  3) Error:
UsersSignupTest#test_valid_signup_information:
ActionView::Template::Error: undefined method `remember_me' for #<User:0x000000074f6ff8>
    app/views/users/new.html.erb:25:in `block (2 levels) in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:24:in `block in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:6:in `_app_views_users_new_html_erb__1810619291483938060_46219160'
    test/integration/users_signup_test.rb:17:in `block in <class:UsersSignupTest>'

^就像在rails教程https://www.railstutorial.org/book/log_in_log_out

中列出8.47一样

看来rails认为:remember_me是一种方法,但为什么???为什么:remember_me被认为是一个方法,当所有其他标签不是???我不想搞定它。

背景:我已经完成了半个ruby教程并进入了这个rails教程。我有非常基本的HTML和CSS能力。以前从未碰过红宝石。我并不真正理解本章中的一半概念。我大多只是按照说明操作。所以,请用noob术语解释:)

2 个答案:

答案 0 :(得分:4)

代码8.47中的表单用于会话:

<%= form_for(:session, url: login_path) do |f| %>

但您的表单适合用户:

<%= form_for(@user) do |f| %>

form_for助手binds a form to an object。当该对象是模型的实例(如@user)时,rails期望每个标签和字段都是该模型的属性。由于remember_me不是User的属性,因此会出错。您可以通过向用户模型添加虚拟属性来解决此问题:

class User < ActiveRecord::Base
  attr_accessor :remember_me
  ...

这样,您就可以在用户表单中使用remember_me,并在提交表单时将params[:user][:remember_me]发送给您的用户控制器。

答案 1 :(得分:1)

您将“复选框”代码放入app/views/users/new.html.erb,这是注册的视图模板,而非登录。

要使代码生效,请将check box代码放入登录视图模板,即app/views/sessions/new.html.erb