Skip to main content

assign_attributes not working

Rails • Asked by Charles Smith


I just signed up for Payments with Stripe and Rails Master Class and am loving it...can't walk away from it; learning a ton!

Having an issue though and was hoping someone could lend a hand. I am following the videos exactly and the only thing I can see that is different is the videos are using the Stripejs form example from Stripe.com whereas I am using Elements. There is an Elements section in the videos which is why I implemented it, but the videos continue without it. Either way, things seem to be working ok, well - until this snag. Oh, even with the attributes not being assigned, Stripe is still creating/updating users properly.

I am trying to assign_attributes if params[:card_last4] but the attributes are not saving so I am not able to display card_brand, card_last4 etc.. Below is my code, thank you.

subscriptions_controller

def create
    customer = current_user.stripe_customer
    begin
      subscription = customer.subscriptions.create(
          source: params[:stripeToken],
          plan: params[:plan],
      )

      current_user.assign_attributes(
          card_brand: params[:card_brand],
          card_last4: params[:card_last4],
          card_exp_month: params[:card_exp_month],
          card_exp_year: params[:card_exp_year]
      ) if params[:card_last4]
      current_user.assign_attributes(stripe_subscription_id: subscription.id)

      current_user.save

      flash.notice = 'Thank you for subscribing'
      redirect_to root_path
    rescue Stripe::CardError => e
      flash.alert = e.message
      render action: :new
    end
  end

views/subscriptions/new.html.erb

<h1>Subscribe</h1>
<%= form_tag subscription_path, id: 'payment-form' do |form| %>
  <div class="form-row">
    <label for="card-element">
      Credit or debit card
    </label>
    <div id="card-element">
      <!-- a Stripe Element will be inserted here. -->
    </div>
    <%= hidden_field_tag :plan, params[:plan] %>
    <!-- Used to display Element errors -->
    <div id="card-errors" role="alert"></div>
  </div>

  <button>Submit Payment</button>

<% end %>

In my addFieldToForm function, I had hiddenInput.setAttribute('name', "user[card_" + field + "]"); but after changing it to hiddenInput.setAttribute('name', "card_" + field); it works as expected.

Gravatar Chris Oliver commented on : Mod Staff

Subtle one! Good catch.

Sometimes I have done virtual attributes on the User (like "user[card_"+field+"]")) and other times just directly accessing the param. It doesn't really make a difference which way you go, but the virtual attributes can make it nice to assign all the fields and then do the saving in a method on the model rather than in the controller.

Login or create an account to join the conversation.