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

前端 未结 3 1749
名媛妹妹
名媛妹妹 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条回答
  •  萌比男神i
    2021-01-12 14:21

    Why are you exposing it as name at all ?

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

    Then you use @model.decrypted_name instead of @model.name as name is encrypted, and such saved in DB.

    edit.haml
    =@user.decrypted_name
    =form_for @user, html: { multipart: true } do |f|
      =f.text_field :decrypted_name
    

    And name if it is encrypted should not be handled directly but with this decrypted_name accessor.

提交回复
热议问题