Ask A Question


You’re not receiving notifications from this thread.

assign_attributes not working

Charles Smith asked in Rails

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

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.


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.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,168+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.