We've moved discussions to Discord

What's the best way to check if a user is subscribed to a plan?

Benjamin Houy
Hi,

I realize this is a pretty basic question but I'm not quite sure what the answer is. 

I have a lessons controller and would simply like to only allow access to the lessons to people who have an active plan.

I saw several threads saying that I should simply run current_account.subscribed? to check if a user is subscribed to any plan but it gives me a nomethod error.

So instead, I added the following in my lessons_controller:
before_action :require_subscription
And then the following in the application_controller:
def require_subscription
  redirect_to pricing_path, alert: "You aren't subscribed to any plan." unless user_signed_in? && current_account.payment_processor&.subscribed?
end

And it seems to work but I have a feeling I may be doing it the wrong way and would love some feedback.

Is this the best way to do it?

Thanks


Bryan Stewart
I had some luck adding this to the current_helper.rb

  def current_subscriber?
    current_account.subscription_ids.length > 0
  end

Then in the show.html.erb
<div class="p-8 bg-white rounded shadow">
    <% if user_signed_in? && current_subscriber? %>
      <%= render @video %>
    <% else %>
      <%= link_to "Subscribe to watch this video", pricing_path, class: "btn btn-primary" %>
    <% end %>
  </div>
Patrick Ward
There is a built-in concern for subscription status that you can use. I think it may have changed at some point in the past. It's now included in the ApplicationController by default. The actual module is located in app/controllers/concerns/accounts/subscription_status.rb.

To use it in a controller or helper call subscribed? or not_subscribed? with or without the product name: 
<%= if subscribed? %>
  <%= render @video %> 
<% else %>
  <%= link_to ... %>
<% end %>
Notifications
You’re not receiving notifications from this thread.