Search code examples
ruby-on-rails-4before-filter

Ruby on Rails: Adding before_filter to check users belong to the same group


I am using ruby 2.0.0p247 and rails 4. I need to add a before_filter in the users controller of my App to check whether users belong to same Group before they call methods on other users like (show). I do not want to use gems in my app. Any Help is appreciated.. Thanks


Solution

  • before_filter :check_for_group, only: [:show] #or add the actions you want here
    

    then at the bottom create a private method to check if 2 users are in the same group

    def check_for_group
      user_getting_shown = User.find(params[:id])
      user_getting_shown.gorups.in?(current_user.groups) # => assuming you have a current_user method that retrives the user session.
    end
    

    However if you need a lot of authorization in your app instead of using before_filters you can create just one in application controller called authorize and then create a separate permission class where you can control all the authorization logic from.It is much easier to test.Ryan bates has 2 awesome screencasts on this subject that you should check out

    http://railscasts.com/episodes/385-authorization-from-scratch-part-1

    http://railscasts.com/episodes/385-authorization-from-scratch-part-1