Rails存储方法将布尔值转换为字符串



我有一个像这样存储布尔属性的类:

class Robot
  store :options, accessors: [:hairy, :smart]
  after_initialize :set_defaults
  private
    def set_defaults
      self.hairy ||= false
      self.smart ||= true
    end
end

我试图用button_to方法更新这些布尔值,但我的布尔值正在被转换为存储哈希中的字符串。我的默认值是:

#<Robot id: 3, options: {"hairy"=>false,"smart"=>true} >

但这:

<%= button_to 'Make hairy', robot_path(@robot, hairy: true), method: :patch %>

将"hairy"变成字符串:

#<Robot id: 3, options: {"hairy"=>"true","smart"=>true} >

我需要显式地指定新的布尔值,所以我不想循环遍历参数和切换!如何防止值变成字符串?

不确定在什么时候这些字符串成为应用程序中的问题,但是覆盖默认访问器是一个解决方案吗?

def hairy
  super.downcase == 'true'
end
def smart
  super.downcase == 'true'
end

在Rails文档中有更多信息:http://api.rubyonrails.org/classes/ActiveRecord/Store.html

我最终决定的解决方案是:

class Robot
  before_save :booleanize
  private
    def booleanize
      self.options.each { |k, v| self.options[k] = to_boolean(v) }
    end
    def to_boolean(str)
      str == 'true'
    end
end

按钮将"true"或"false"作为字符串修补,但是before_save钩子将遍历每个选项并将其转换为相应的布尔值。

最新更新