Ruby on rails Rails序列化哈希-是否可以指定数据类型?

Ruby on rails Rails序列化哈希-是否可以指定数据类型?,ruby-on-rails,serialization,Ruby On Rails,Serialization,我正在将表单输入序列化为哈希。有可能将一些输入强制转换成整数吗 例如,如果我执行@user.update_属性(params[:user]),其中一个参数应该是一个数字,那么该数字将被存储为一个类似“123”的字符串 是否可以确保它存储为整数 要明确的是: 我的用户模型看起来像 class User < ActiveRecord::Base ... store :preferences, accessors: [:max_capacity] ... end class用户

我正在将表单输入序列化为哈希。有可能将一些输入强制转换成整数吗

例如,如果我执行@user.update_属性(params[:user]),其中一个参数应该是一个数字,那么该数字将被存储为一个类似“123”的字符串

是否可以确保它存储为整数

要明确的是:

我的用户模型看起来像

class User < ActiveRecord::Base
  ...
  store :preferences, accessors: [:max_capacity]
  ...
end
class用户
我的表单可能会有这样的输入

<input name="user[preferences][max_capacity]" type="text"/>


这将导致最大容量存储为字符串。我可以在存储时强制它为整数吗?

您可以在保存之前直接修改存储在params散列中的用户对象。如果将最大容量从字符串转换为整数,则需要考虑用户提交的最大容量值不正确的情况。这可以通过启动/救援模块进行处理

在控制器操作中,您可以执行以下操作:

def update
  max_capacity = params[:user][preferences][max_capacity]
  begin
    # Attempt to convert into an integer
    Integer(max_capacity)
  rescue
    # If max_capacity was incorrectly submitted: 'three', '04', '3fs'.
    redirect_to edit_user_path, :alert => "Unable to update user. Invalid max capacity."
  else
    If it can be converted, do so, and update the user object in the params hash.
    params[:user][preferences][max_capacity] = Integer(max_capacity)
  end

  @user.update_attributes(params[:user])
        .
        .
        .
end