rmm5t/strip_attributes

strip_attributes not working with Form Object

jaredlt opened this issue · 1 comments

I have created a custom Form Object and am trying to use strip_attributes with no luck.

class PaymentSessionForm
  include ActiveModel::Model
  include ActiveModel::Validations::Callbacks # added based on ActiveAttr example in readme
  
  attr_accessor(:name, :email, :amount, :message:, :event_id)

  strip_attributes
end

I think my issue is that I'm not saving this model to the db, rather I'm just validating it then using the values to create an object of the database model, which then saves it.

My controller:

class PaymentSessionsController < ApplicationController

  def create
    # Using form object so can have different form validations compared to model validations
    # eg. valid form amount == 10.23, but valid model amount is 1023 (integer)
    @payment_session_form = PaymentSessionForm.new(payment_session_form_params)

    respond_to do |format|
      if @payment_session_form.valid?

        stripe_session = stripe_session(@payment_session_form)

        @payment_session = PaymentSession.new( # model associated to db
          name: @payment_session_form.name, 
          email: @payment_session_form.email, # these values are not stripped
          amount: @payment_session_form.amount.to_minor_currency_unit, 
          message: @payment_session_form.message, 
          checkout_session_id: stripe_session["id"], 
          event_id: @payment_session_form.event_id 
        )

        @payment_session.save

        format.js
      else
        format.js
      end
    end
  end
end

Any help would be appreciated.

rmm5t commented

Hi @jaredlt. The problem in this case (I believe) is that you're using attr_accessor instead of attributes on the model.

See ActiveModel::Attributes for more info:
https://api.rubyonrails.org/classes/ActiveModel/Attributes/ClassMethods.html