简体   繁体   中英

Users belong to organisations and only see/edit items added by their company Ruby on Rails

Trying to figure out the best way of organising users into organisations so that the members of each organisation only see items added by themselves and other people from their organisation. All users need to use a shared login.

I have some previous experience with Devise so would like to use it if possible.

What is the best way of tackling this issue?

Any links to tutorials explaining this would be great.

Thanks

Let's assume you have user model that belongs to some company:

class User < ActiveRecord
  belongs_to :company
  ....
end

company model has many users and has many products(items):

class Company < ActiveRecord
  has_many :users
  has_many :products
end

product model that belongs to company:

class Product < ActiveRecord
  belongs_to :company
  ....
end

In your case, what you're trying to achieve is that user can see/edit only products from his company. Using before_action in your controller you can define what user can/cannot do. Here is the basic example:

class ProductsController < ApplicationController
  before_action :authorize_user, only: [:show, :edit]

  def show  
  end

  def edit 
  end

  private
  def authorize_user
   raise "Not Authorized" unless current_user.company_id == @product.company_id
  end
end

This way you will raise an error whenever user try to access the product that doesn't belongs to his company.

Ofcourse, this is just basic example, you should take a look on Pundit gem which is very powerful, but you should get the point with this :)

Let me know if I missed something.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM