Ask A Question

Notifications

You’re not receiving notifications from this thread.

What is the best way to work with user roles?

Samantha O asked in Rails

What is the best way to achieve this when people sign up? I have a user model and an account model. I want to have 3 roles in my application. The administrator, store_owner and end_user.

A store owner can add a store.
The end_user sees all the stores that a store_owner has added.
The administrator sees everything :)

For now I have:

  class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :validatable

  enum type: [:administrator, :store_owner, :end_user]
  enum gender: [:male, :female]
end


class Account < ApplicationRecord
  enum status: [:active, :inactive, :expired, :locked]
  has_many :users

  before_create :set_api_key
  accepts_nested_attributes_for :users


  private
  def self.generate_api_key
    SecureRandom.hex(36)
  end

  def set_api_key
    self.api_key = Account.generate_api_key
  end
end

And in my signup view:

<%= form_for @account do |f| %>
<%= f.fields_for :users do |user| %>
<%= f.label :email %>
<%= user.email_field :email, autofocus: true, autocomplete: "email", placeholder: "name@address.com" %>
<%= f.label :password %>
<% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %>
<%= user.password_field :password, autocomplete: "new-password", placeholder: "Password" %>
<%= f.label :password_confirmation %><br />
<%= user.password_field :password_confirmation, autocomplete: "new-password", placeholder: "Password" %>
<%= f.submit "Sign up" %>

In my accounts controller:

class AccountsController < ApplicationController
  def index
  end

  def new
    @account = Account.new
    @account.users.build
  end

  def create
    @account = Account.new(account_params)

    if @account.save
      sign_in @account.users.first, bypass: true
      redirect_to root_path
   else
      render :new
  end
end

  def destroy
    @account = Account.find(params[:id])
    @account.destroy
    redirect_to root_path, notice: "Account deleted."
  end

  private

  def account_params
    params.require(:account).permit(users_attributes: [:email, :password, :password_confirmation])
  end
end
Reply

So the question is, how do I make separate signups for store_owner and end_user? An example of this would be something like airbnb...There you can be a host (someone who rents out their home, or someone who rents a home from a host).

Reply

I'm interested too

Reply
Join the discussion
Create an account Log in

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

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

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