I'm trying to update the role of a user from 'free' to 'premium' after they successfully make a payment.
User.rb
class User < ApplicationRecord
enum role: [:free, :premium]
before_create :assign_default_role
def assign_default_role
self.role ||= :free
end
end
subscriptions controller
def create
@user = current_user
@subscription = Subscription.new(subscription_params)
if @subscription.save_with_payment
redirect_to @subscription, :notice => "Thank you for subscribing"
@user.update_attribute(role: premium )
else
render :new
end
end
I'm getting this error undefined local variable or method `premium' after trying to make the user makes a payment
Are you sure you don't want premium
to be :premium
? Better yet, how about:
@user.premium!
Personally, I prefer to use the form of enum
:
class User < ApplicationRecord
enum role: {
free: 0,
premium: 1
}
before_create :assign_default_role
def assign_default_role
self.role ||= :free
end
end
For the reasons discussed in the docs.
Finally, perhaps you should consider putting a default on role
(using a migration) so that you don't have to do that before_create
bit.