check if child exists in one to many relation
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.
I'd go for
def require_course
redirect_to root_path if @user.courses.blank?
end
Documentation about Object#blank?
How about current_user.courses.size > 0
?
Even a shorter one:
redirect_to(root_url) if @user.courses.size.zero?
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.
精彩评论