Reputation: 331
I'm trying to figure out at this point how to display only a certain amount of categories based on a user plan. So in my controller I have the following;
def check_plan?
User.current.plan_id == "" && User.current.bins.count == 2 || User.current.plan_id == "nil" && User.current.bins.count == 2
end
helper_method :check_plan?
NOTE: I know, not pretty but it will do for now. So basically :check_plan? checks a few things.
Now I thought, that I could use that for our category list as a starting point, so that if the user isn't on any plan, they are limited in showing 2 if they are on a plan it shows them all. Here's what I thought would work but it doesn't. I've done it before but can't remember exactly how it went, so any help is appreciated.
<% if check_plan? %>
<% @bin_list.order("position").limit(2).each do |bin| %>
<% else %>
<% @bins_list.order("position").each do |bin| %>
<% end %>
Not really working and I know why, but their will all my other tries with bringing any of those lines together with check_plan.
Upvotes: 0
Views: 51
Reputation: 24815
Such logic belongs to Model natually. Don't abuse helper.
class User < ActiveRecord::Base
def bin_limit
check_plan? ? 0 : 2
end
def check_plan?
# Your logic
end
def bins_with_limit
bins.with_limit(bin_limit)
end
end
class Bin < ActiveRecord::Base
def self.with_limit(limit)
return self if limit <=0
self.limit(limit)
end
end
View
current_user.bins_with_limit.each do |bin|
Upvotes: 2
Reputation: 15917
First of all, the rails method .blank?
will return true for either "" or nil, so you can start by refactoring your code as follows:
def check_plan?
( User.current.plan_id.nil? || User.current.plan_id.blank? ) && User.current.bins.count == 2
end
helper_method :check_plan?
Secondly, you're calling blocks in the code below, so you'll need to complete them with end
<% if check_plan? %>
<% @bin_list.order("position").limit(2).each do |bin| %>
<% end %>
<% else %>
<% @bins_list.order("position").each do |bin| %>
<% end %>
<% end %>
Of course, you'll want to put whatever you're doing with bin
between the do
and end
portions above.
Upvotes: 1