attr_encrypted和加密由date_select表单助手生成的日期

时间:2014-05-02 15:51:04

标签: mysql ruby-on-rails ruby encryption attr-encrypted

我是rails的新手,我正在使用Rails 4和attr_encrypted gem加密一些字段(SSN,名称,出生日期等),这些字段将全部插入{{1 }} 列。在表单视图中,我使用varchar生成出生日期字段(dob),但我在尝试将所选日期转换为字符串时遇到问题,以便date_select可以对其进行加密插入数据库。

_form.html.erb

attr_encrypted

给出的错误是质量分配错误,但我不知道如何/在哪里(控制器/模型)将哈希转换为字符串,以便<%= f.label :dob %><br> <%= f.date_select :dob, { start_year: 1900, :order => [ :month, :day, :year ] , prompt: true, add_month_numbers: true, use_two_digit_numbers: true } %> gem能够加密它。实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

我发现attr_encrypted打破了Rails&#39;自date_select的日期自动组合。我发现最简单的解决方案是自己组装日期字符串并重写params哈希。在您的控制器中:

protected    

def compose_date(attributes, property)
  # if the date is already composed, don't try to compose it
  return unless attributes[property].nil?

  keys, values = [], []

  # find the keys representing the components of the date
  attributes.each_key {|k| keys << k if k.start_with?(property) }

  # assemble the date components in the right order and write to the params
  keys.sort.each { |k| values << attributes[k]; attributes.delete(k); }
  attributes[property] = values.join("-") unless values.empty?
end

然后你可以正常进行,一切都会好的:

def create
  compose_date(params[:client], "dob")

  @client = Client.new(params[:client])
  ...
end

编辑:我最初忘记了这一点,但我必须做一些额外的工作才能在数据库中正确存储日期。 attr_encrypted gem始终要存储字符串,因此如果您的数据不是字符串,那么您将要向它展示如何编组它。

我创建了一个处理数据加密的模块:

module ClientDataEncryption
  def self.included(base)
    base.class_eval do
      attr_encrypted :ssn, :key => "my_ssn_key"
      attr_encrypted :first_name, :last_name, :key => "my_name_key"
      attr_encrypted :dob, :key => "my_dob_key",
                     :marshal => true, :marshaler => DateMarshaler
    end
  end

  class DateMarshaler
    def self.dump(date)
      # if our "date" is already a string, don't try to convert it
      date.is_a?(String) ? date : date.to_s(:db)
    end

    def self.load(date_string)
      Date.parse(date_string)
    end
  end
end

然后将其包含在我的客户端模型中。

答案 1 :(得分:0)

我正在撰写一份贷款申请表,并在attr_encrypted模型的Owner属性date_of_birth上遇到了同样的问题,导致我来到这里。我发现Wally Altman的解决方案几乎是完美的,需要在我的应用程序中进行一些更改:

  • 以嵌套形式使用
  • 强参数
  • 多个模型实例

我逐字复制了DateMarshalercompose_date()方法,然后在我的控制器中添加了一个循环,遍历我们在此处编辑的所有Owner个对象。< / p>

def resource_params
  params[:loan_application][:owners_attributes].each do |owner| 
    compose_date(owner[1], 'date_of_birth')
    # If there were more fields that needed this I'd put them here
  end
  params.require(:loan_application).permit(:owners_attributes =>
    [ # Regular strong params stuff here ])
end

它在任何数量的嵌套模型上都像魅力一样!

相关问题