新手问题 [已经解决,thx] ActiveRecord::Base after_find 的问题 !

u1351384616 · August 29, 2015 · Last by u1351384616 replied at October 05, 2015 · 2016 hits

今天遇到一个奇怪的问题:

代码如下:

class Role < ActiveRecord::Base

  after_find do |record|
    unless record.rule.nil?
      # 转换为hash类型, rule原来是hash字符串
      record.rule = JSON.parse(record.rule)
    end
  end

end

class RolesController < ApplicationController
  def show
    @role = Role.find(1)
    # role.rule 居然是字符串类型
  end
end

rule 在数据库中定义的类型是 string 我想在查询之后,通过 after_find 回调把 rule 的字符串转换为 hash,但是问题出现了,在 controller, 或者 view 中是使用@role.rule的时候,rule 居然还是字符串类型的???? 各位,有没有遇到过类似的问题,看看如何解决

楼主你的用法不对,这里 after_find 应该是执行了的,因为 record.rule 在数据库中是 text 类型,所以在 record.rule 重新赋值的时候还发生了一次隐性的类型转换,相当于

record.rule = JSON.parse(record.rule).to_s

如果你真的想存 JSON 格式,从数据库中取出来的时候转 Hash 的话,建议你 JSON 类型的 serialize

http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html

這個地方應該使用 serialize

class Role < ActiveRecord::Base
   serialize :rule, JSON
end

@fumesy 太感谢了,学习了,%>_<%

学习。。。

#2 楼 @fumesy 这种方式感觉 json 数组不行?find 出来之后还是字符串

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