0

I have a situation where i wish to show a link on if someone has never created an event (invite) or if the last invite was more than 30 days ago.

However, this code wont work;

<% if current_user.invites.nil? || ( current_user.invites && (Date.today - current_user.invites.last.created_at) >= 30.days) %> 

<% end %>

Someone help me re-organise this in a way that works especially the conditions after the OR option.

thank you

acacia
  • 1,375
  • 1
  • 14
  • 40

1 Answers1

2

Since current_user.invites returns an array, you should not use .nil? because arrays with no items are not nil, are empty, so this invites array will be empty ([]) when has no items, so you can use #empty?.

Also I removed the second condition because there is no need to check if the invites is not empty. In other words, if the invites array is empty, the right side of the OR (||) condition is not going to be evaluated.

<% if current_user.invites.empty? || (Date.today - current_user.invites.last.created_at) >= 30.days %> 

<% end %>

I would also recommend you to extract this code in a custom helper method, so your code will be a little more DRY.

# app/helpers/my_helper.rb
module MyHelper
  def invites_created_after_or_none?(user = current_user, days = 30.days)
    user.invites.empty? || (Date.today - user.invites.last.created_at) >= days
  end
end

<% if invites_created_after_or_none? %> 

<% end %>
Rafa Paez
  • 4,820
  • 18
  • 35
  • i suggest using `blank?` instead of `empty?` as it's more generic http://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails – a14m Mar 22 '14 at 22:53
  • 1
    IMHO, for arrays sound much better `empty?` than `blank?` I also prefer using pure Ruby methods if possible and there is no gain, and `empty` is implemented in Rails. – Rafa Paez Mar 22 '14 at 22:59