Skip to main content

assign_attributes not working

Rails • Asked by Charles Smith

Charles Smith (850 XP) on

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 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.


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

          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]

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


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

  <button>Submit Payment</button>

<% end %>

Charles Smith (850 XP) on

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.

Chris Oliver (163,510 XP) on

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.