如上, get 请求/articles/new 点击点击创建后,进入 create method,关联上当前用户创建 ariticle 并 save,这里的两个 flash 变量,始终无法传递到 redirect_to 后的 show 方法?
但是 RoR 明明是这么说的: By default, adding values to the flash will make them available to the next request,
不知大家有没有遇到过?
HomeController < ... def from flash[:n] = 'set flash[:n] in home#from' flash.keep(:n) redirect_to '/to' end
def to end end router:
match 'from' => 'home#from' match 'to' => 'home#to'
view:
<%= flash[:n] %>
经过上面 create 那段逻辑后,这里请求 /from 跳转后的页面也为空
登出后,请求/from flash 工作恢复正常,再次登入也正常,但是走过一次 create 逻辑后,一切又失败了
登出逻辑:
def logout session[:current_user] = nil redirect_to '/login' end
config/initializers/session_store.rb
Blog::Application.config.session_store :active_record_store
难道是这边我的误用?
Redirected to http://localhost:3000/articles/33 Completed 302 Found in 15ms (ActiveRecord: 3.2ms)
Started GET "/articles/33" for 127.0.0.1 at 2013-03-29 15:52:10 +0800
Processing by ArticlesController#show as HTML
Parameters: {"id"=>"33"}
Article Load (0.3ms) SELECT articles
.* FROM articles
WHERE articles
.id
= 33 LIMIT 1
Rendered articles/show.html.erb within layouts/application (0.2ms)
Completed 200 OK in 6ms (Views: 4.1ms | ActiveRecord: 0.3ms)
我又加了再 show 里加了一段 debug,却是 flash 被清空了
========in articles@show#, @closed=false, @flashes={}, @now=nil>
#13 楼 @Rei 不会重名 在 show action 加上
flash[:n] = 'set flash[:n] in articles#show'
debug 出这段
========in articles@show#, @closed=false, @flashes={:n=>"set flash[:n] in articles#show"}, @now=nil>
且 view 里的 flash[:n] 也生效了,一般不是要下面这种方式 same request 才生效的么?
flash.now[:n] = '....' 竟然改变了 flash 的默认 next request show 的行为
#15 楼 @Rei 这段竟然会报 undefined method `[]' for nil:NilClass?
logger.debug session
再 create 开头和 redirect 之前及 show 方法里安置 debug
输出:
========step1 in articles#create #, @closed=false, @flashes={}, @now=nil> #User:0x007fe0c6138298
========step2 in articles@create #, @closed=false, @flashes={:article=>#
, :n=>"dfasdfds"}, @now=nil> #User:0x007fe0c6138298========in articles#show #, @closed=false, @flashes={}, @now=nil> #User:0x007fe0c62403c0
jiadongkais-MacBook-Pro:blog jiadongkai$ rails -v Rails 3.2.12 jiadongkais-MacBook-Pro:blog jiadongkai$ ruby -v ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin12.3.0] jiadongkais-MacBook-Pro:blog jiadongkai$ gem -v 2.0.3
复现步骤:
git clone https://github.com/tiemei/blog.git cd blog bundle install (修改 database.yml) rake db:migrate rails server
http://localhost:3000/users/new 注册新用户 http://localhost:3000/login 登陆 http://localhost:3000/articles/new 填写内容提交
发现问题了
> ActiveRecord::SessionStore::Session.last.data
ActiveRecord::SessionStore::Session Load (0.2ms) SELECT `sessions`.* FROM `sessions` ORDER BY `sessions`.`id` DESC LIMIT 1
ArgumentError: undefined class/module User
Session 在反序列化的时候,找不到 User 和 Article 类,导致解析失败。开发环境下 Model 每次都需要重新载入。
Session 里面不放对象是好习惯,如果一定要放就要打补丁,比较麻烦我就不说了。