Reputation: 11
User model: has_many :courses
Course model: belongs_to :user
def require_course
unless #check if current user has course
redirect_to root_url
return false
end
end
i need a method that checks if current user has courses. What should i write to check if current_user has course.
Upvotes: 1
Views: 2700
Reputation: 1790
I'd go for
def require_course
redirect_to root_path if @user.courses.blank?
end
Documentation about Object#blank?
Upvotes: 2
Reputation: 11038
Or even shorter:
def require_course
redirect_to root_url if @user.courses.empty?
end
(note the root_url
instead of root_path
, as discussed here.
Upvotes: 0
Reputation: 14973
Even a shorter one:
redirect_to(root_url) if @user.courses.size.zero?
Upvotes: 0