RailsCasts Pro episodes are now free!

Learn more or hide this

Chris Grant's Profile

GitHub User: interhive

Site: http://interhive.net/

Comments by Chris Grant


The params hash is used to get data that's been posted from a form. You may have seen params being sent back to the browser but that's typically used to re-display a form using data that's already been sent (i.e. when a person has forgotten to input a field).

You can probably set the plan_id using the params hash but it's more work and isn't the idiomatic 'Rails Way.'

See: ActionController : Parameters


Yeah, the build method is ActiveRecord magic. Good magic! :)

In your code (@plan_id = params[:plan_id]), the params[:plan_id] is not going to do what you think. The first time the form is shown, params[:plan_id] is going to be nil -- it doesn't exist in the params hash (yet) because it hasn't been set to anything.

It's best to use the build method. It saves you from these bugs that are hard to track down.

Either way, you get the gist of what's going on.


The hidden plan_id field is actually set because of the call to plan.subscriptions.build method. Without that call, :plan_id hidden field within the form would be nil.

You're using the build method to set that value within the form. That way, when you call the Subscription.new method using the params hash, it will know which plan the subscription is associated with.


Regarding question 3...

It has to do with the model associations.

When you say:

@subscription = plan.subscriptions.build

you are really saying something like:
@subscription = Subscription.new(plan_id: id)

You are wanting an object that already has the association (to a particular Plan, in this case) set. This object is passed to the form with the association set -- so it knows how this particular Subscription object relates to a specific Plan object.

see: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html



Regarding question 2...

You can see that Ryan adds a stripe_customer_token to the subscription model:

rails g migration add_stripe_to_subscriptions stripe_customer_token:string

self.stripe_customer_token = customer.id sets that in the current subscription object (taken from the object returned by Stripe::Customer.create() method).

Hope that helps!


Great video on a great service. For those outside the US, know that Stripe is working on it. :)

Stripe on HackerNews