Search code examples
ruby-on-railspermissionscancanscopescancancan

Rails CanCanCan & Defining Abilities


I am trying to make an app in Rails 4.

I am using CanCanCan for permissions and Role_Model for roles management.

In my ability.rb, I have defined student abilities as:

 elsif user.try(:profile).present? && user.profile.has_role?(:student)

      student_abilities

and then:

def student_abilities
can :read, Project.visible.current.available

In my project.rb I have defined scopes as:

    scope :visible, lambda { joins(:sweep => :disclosure).where('disclosures.allusers' => 'true')
        .joins(:sweep => :finalise).where('finalises.draft' => 'false') }
  scope :current, lambda { where('project.start_date >= ?', Date.today)}
  scope :available, lambda { where('closed =', 'false')}

When I try to start the server and generate a view, I get this error:

NoMethodError at /project_invitations
undefined method `available' for #<Project::ActiveRecord_Relation:0x007fdde41f2ee8>

When I try removing available from the end of the ability, so that its just:

can :read, Project.visible.current

I get this error:

 entry for table "project"
LINE 1: ..." = 'true' AND "finalises"."draft" = 'false' AND (project.st...
                                                             ^

I don't know why it won't let me read the end of the error message.

Can anyone see what I've done wrong?


Solution

    1. Check the table name. Is it really called "project", not "projects"?

    2. The way you describe scopes is a bit weird. E.g. instead of where('closed =', 'false') I would describe it as where(closed: false), minimizing the number of SQL-aware fragments