`form_for` is bypassing model accessors. How to make it stop? (Or: How to make a custom attribute serializer?)

前端 未结 3 1732
名媛妹妹
名媛妹妹 2021-01-12 13:14

I set these methods to automatically encrypt values.

class User < ApplicationRecord
  def name=(val)
    super val.encrypt
  end
  def name
    (super()          


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-12 14:13

    I found this similar question: How do input field methods (text_area, text_field, etc.) get attribute values from a record within a form_for block?

    I added

      def name_before_type_cast
        (super() || '').decrypt
      end
    

    And now it works!

    Here is the full solution:

      @@encrypted_fields = [:name, :phone, :address1, :address2, :ssn, ...]
      @@encrypted_fields.each do |m|
        setter = (m.to_s+'=').to_sym
        getter = m
        getter_btc = (m.to_s+'_before_type_cast').to_sym
        define_method(setter) do |v|
          super v.encrypt
        end
        define_method(getter) do
          (super() || '').decrypt
        end
        define_method(getter_btc) do
          (super() || '').decrypt
        end
      end
    

    Some docs: http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/BeforeTypeCast.html

提交回复
热议问题