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 %>
Join 31,575+ developers who get early access to new screencasts, articles, guides, updates, and more.