title: defining abilities (CanCan) with has_many :through association
body: <p>I am a beginner in rails and have been trawling through many suggested answers to this problem. I can't seem to translate the answers, I've seen to my situation. I'm hoping someone would be kind enough to shed some light on it.
  The 2 models, I am concerned with are User and Project. Each User can create a project, but each user can also manage a project. To allow for this, I have created a has_many :through relationship between <strong>User</strong> and <strong>Project</strong>, using a managing model to connect the two models.</p>
  
  <p>user.rb</p>
  
  <pre><code> has_many :managings, foreign_key: "manager_id", dependent: :destroy
   has_many :managed_projects, through: :managings
  </code></pre>
  
  <p>managing.rb</p>
  
  <pre><code>belongs_to :manager, class_name: "User"
  belongs_to :managed_project, class_name: "Project"
  </code></pre>
  
  <p>project.rb</p>
  
  <pre><code>has_one :reverse_managing, foreign_key: "managed_project_id",
                                  class_name:  "Managing",
                                  dependent:   :destroy
  has_one :manager, through: :reverse_managing, source: :manager
  </code></pre>
  
  <p>So, I have a role called 'Beginner'. Beginners can only read projects, with the exception of those who choose to be managers of a project. Managers should also be allowed to edit and update a project, which they are managing.</p>
  
  <p>Below is my attempt at this in ability.rb</p>
  
  <pre><code> user ||= User.new # guest user (not logged in)
    if user.role? :Admin
      can :manage, :all
    elsif user.role? :Author
      can :read, :all
      can [:create], [Project]
      can [:edit, :update], Project, :user_id =&gt; user.id
    elsif user.role? :Beginner
     can :read, :all
  
     can [:edit, :update], Project, :manager_id =&gt; user.id
    end
  </code></pre>
  
  <p>The last line doesn't appear to be working, as I am not seeing an edit link when I look at the project view of a beginner who is managing that project.</p>
  
  <p>Here is the code that I use in the view:</p>
  
  <pre><code>&lt;% if can? :update, project  %&gt;
  &lt;%= link_to 'Edit', edit_project_path(project) %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>and this is what appears in projects_controller</p>
  
  <pre><code>def edit
    @project = Project.find(params[:id])
    authorize! :edit, @project
  end
  </code></pre>
  
  <p>I will sleep a happy man if someone can help me on this</p>
  
  <p>UPDATE</p>
  
  <p>here is the role? method in User.rb</p>
  
  <pre><code>def role?(role)
    return !!self.roles.find_by_name(role.to_s.camelize)
  end
  </code></pre>
  
  <p>UPDATE</p>
  
  <p>I had the wrong role_id assigned to the user. After correcting this, I got an error message, when I tried to open the project view containing the edit link.</p>
  
  <pre><code>undefined method `manager_id' for #&lt;Project:0xb387f0b0&gt;
  </code></pre>