Genk
Genk

Reputation: 11

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.

Upvotes: 1

Views: 2700

Answers (4)

Pasta
Pasta

Reputation: 1790

I'd go for

def require_course
   redirect_to root_path if @user.courses.blank?
end

Documentation about Object#blank?

Upvotes: 2

Sam Ritchie
Sam Ritchie

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

edgerunner
edgerunner

Reputation: 14973

Even a shorter one:

redirect_to(root_url) if @user.courses.size.zero?

Upvotes: 0

David Sulc
David Sulc

Reputation: 25994

How about current_user.courses.size > 0 ?

Upvotes: 0

Related Questions