All threads / Pundit Policy and has_many through Pt. II

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Pundit Policy and has_many through Pt. II

Ivor Padilla asked in General

Hey there,

I decided to start another post although I read this one already https://gorails.com/forum/pundit-scope-and-has_many-through but I need to confirm that my query is on point.

Here's my three models:

class Project < ActiveRecord::Base
  has_many :collaborations
  has_many :users, through: :collaborations
end
class Collaboration < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end
class User < ActiveRecord::Base
 has_many :collaborations
 has_many :projects, through: :collaborations
end

What I need is to allow project.user (in this case the project creator) OR project.collaborators to see their list of projects. What I'm looking is for a way to improve this query: scope.joins(:users).where('collaborations.user_id = ? OR projects.user_id = ?', user, user)

  class Scope < Scope
    def resolve
      return scope.all if user.has_role?(:admin) && user.present?
      scope.joins(:users).where('collaborations.user_id = ? OR projects.user_id = ?', user, user)
    end
  end
  def add_member_to_project
    @project = Project.friendly.find(params[:project_id])

    if @project.update_attributes(project_params)
      user_ids = params[:project][:user_ids]

      user_ids.map do |user_id|
        @project.collaborations.build(user_id: user_id)
      end

      flash[:notice] = "Member added."
      redirect_to @project
    else
      flash[:danger] = "Member couldn't be added"
      render 'show'
    end
  end
<%= form_for @project, :url => add_member_to_project_path  do |f| %>
  <%= f.collection_check_boxes(:user_ids, @members, :id, :name) %>
  <%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>  

Thank you!

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 34,674+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.