Rails 最近升级了 Rails 到 4.2.3,似乎发现了一个 Bug [已解决]

tumayun · July 10, 2015 · Last by tumayun replied at July 11, 2015 · 2373 hits

升级完后出现了个错误如下:

> undefined method `length' for nil:NilClass

app/views/api/messages/unread.json.jbuilder, line 1

 - actionview (4.2.3) lib/action_view/helpers/cache_helper.rb:189:in `write_fragment_for'
 - actionview (4.2.3) lib/action_view/helpers/cache_helper.rb:179:in `fragment_for'
 - actionview (4.2.3) lib/action_view/helpers/cache_helper.rb:115:in `cache'
 - app/views/api/messages/unread.json.jbuilder:1:in `_app_views_api_messages_unread_json_jbuilder___3570167334891618967_70131777006720'
 - actionview (4.2.3) lib/action_view/template.rb:145:in `block in render'

经调查在 view 中使用 cache 的时候,不知为何 output_buffernil ,感觉不像是 Rails 的 Bug,可能是 Jbuilder 之类的原因,具体原因还未找到。 请大家也试试自己的应用,看是否有相同的问题。

# actionview-4.2.3/lib/action_view/helpers/cache_helper.rb#186
def write_fragment_for(name, options) #:nodoc:
  # VIEW TODO: Make #capture usable outside of ERB
  # This dance is needed because Builder can't use capture
  pos = output_buffer.length
  yield
  output_safe = output_buffer.html_safe?
  fragment = output_buffer.slice!(pos..-1)
  if output_safe
    self.output_buffer = output_buffer.class.new(output_buffer)
  end
  controller.write_fragment(name, fragment, options)
end

Update

这个问题排查了半天,回到升级前的版本一样出问题,经仔细比对代码,原来是我把 json.cache! 给误删成 cache 了! 真是脑残了,大家引以为戒~~

你的代码呢?发出来看看

cache [:unread_messages, params[:version], current_user.id, current_user.unread_messages_received_at.value, @messages.limit_value, @messages.current_page] do
  json.messages do
    json.array! @messages, partial: 'api/messages/message', as: :message
  end

  json.current_page @messages.current_page
  json.per_page     @messages.limit_value
  json.count        @messages.total_count
end

jbuilder 的代码看起来没什么问题,奇怪

@huacnlee 脑残了~~ 要写成 json.cache!

You need to Sign in before reply, if you don't have an account, please Sign up first.