Temp

How to create a new role in Solidus or Spree

Jul 19, 2018 by ohiodn8




In this tutorial we will be adding a new role to a solidus project. At the moment my project is built on the solidus gem, but then, the solidus gem is built on spree. So, this tutorial will work for a spree or solidus project. 


A solidus/spree user defines only one role with cancan (or cancancan) - admin. You can check this by running rails console in the root of your project folder (on the terminal/cmd), and inside the console run=> 

Spree::Role.all

That should be fine to view the admin role with an id of 1, or it may prompt you to run Spree::Role.connection, and then  Spree::Role.all


CREATING A NEW ROLE

Still in the rails console, run =>

Spree::Role.create(name: 'vendor')

This will create a new role - vendor, and you can close the console.


Head over to your application folder and create  app/models/spree/ability.rb =>

require 'cancan'
module Spree
  class Ability
    include CanCan::Ability

    class_attribute :abilities
    self.abilities = Set.new

    # Allows us to go beyond the standard cancan initialize method which makes it difficult for engine
    def self.register_ability(ability)
      abilities.add(ability)
    end

    def self.remove_ability(ability)
      abilities.delete(ability)
    end

    def initialize(user)
      clear_aliased_actions

      # override cancan default aliasing (we don't want to differentiate between read and index)
      alias_action :delete, to: :destroy
      alias_action :edit, to: :update
      alias_action :new, to: :create
      alias_action :new_action, to: :create
      alias_action :show, to: :read
      alias_action :index, :read, to: :display
      alias_action :create, :update, :destroy, to: :modify

      user ||= Spree.user_class.new

      if user.respond_to?(:has_spree_role?) && user.has_spree_role?('admin')
        can :manage, :all
      elsif user.respond_to?(:has_spree_role?) && user.has_spree_role?('vendor') 
        can :manage, User
        can :manage, Product  
      else
        can :display, Country
        can :display, OptionType
        can :display, OptionValue
        can :create, Order
        can :read, Order do |order, token|
          order.user == user || order.token && token == order.token
        end
        can :update, Order do |order, token|
          !order.completed? && (order.user == user || order.token && token == order.token)
        end
        can :display, CreditCard, user_id: user.id
        can :display, Product
        can :display, ProductProperty
        can :display, Property
        can :create, Spree.user_class
        can [:read, :update, :destroy], Spree.user_class, id: user.id
        can :display, State
        can :display, Taxon
        can :display, Taxonomy
        can :display, Variant
        can :display, Zone
      end
      
      

      # Include any abilities registered by extensions, etc.
      Ability.abilities.merge(abilities_to_register).each do |clazz|
        merge clazz.new(user)
      end

      # Protect admin role
      cannot [:update, :destroy], Role, name: ['admin']
    end

    private

    # you can override this method to register your abilities
    # this method has to return array of classes
    def abilities_to_register
      []
    end
  end
end

In here, you gave the admin role the ability to manage all your resources and gave the vendor role the ability to mange your product and user resources.


Start your server and head over to =>

http://localhost:3000/admin

Login with your admin password and create a new user account. Beneath the email link, you should see admin and vendor. Select vendor (input the new email and password for the vendor account) and create. 


Now logout of your admin account, and head back to => 

http://localhost:3000/admin

This time use the vendor account details that you just create and you'll be greeted with image below =>



Ignore the Authorization Failure error, and click on the Products and Users tab on the left side of the screen. To give your vendor role more functionality/ability, edit your the ability.rb file. 


(Hope I covered everything!)



About ohiodn8

Ruby on Rails developer, AWS Engineer, anything fun, music, a little bit of mobile game. . .

Comments (21)

Teen Girls Pussy Pics. Hot galleries
http://girlxxxwith.digos.jsutandy.com/?anabel
forum streaming porn grandma riding porn free big male porn brunswick anal porn teen pad porn

3 days ago by louellaad3

These canvas prints are printed with solvent-free HP latex inks making them safe for all family. Multiple decorative frame designs available! Manually stretched! The Canvas Prints from CanvasDiscount.com are Ready to Ship in 24h & have The Lowest-Price-in-the-USA Guarantee.

Personalize Your Wall with Premium Photo Canvas
Hand-stretched canvas on a real wood frame
Range of striking edge designs available
High-resolution photo printing in vivid colors
UV-resistant inks, totally free of solvents
Canvas certified for professional photo printing

HomaPage : kristendecor Canvas
uc canvas

13 days ago by GeraldWaync

301 Moved Permanently https://rlcpa.com.hk/drp.php - Click here...

14 days ago by DavidNUAMI

Подключайте домашний интернет МТС с максимальной выгодой и честными тарифными планами. Высокая скорость и стабильный интернет, обеспечивают бесперебойное высокоскоротное подключение к домашнему интернету по вашему адресу.

Вам больше не нужно стоять в очередях чтобы подключить домашний интернет МТС, просто оставьте заявку на понравившийся тариф и мы подключим его бесплатно!

18 days ago by Sergeyincex

HostGator Coupon Code 2022

21 days ago by Stevenhit

Чтобы вращать слоты на деньги, нужно зарегистрироваться в онлайн казино. За регистрацию вы получите регистрационный бонус, обычно это бесплатные вращения за регистрацию и процентный бонус на первый депозит. Ещё online casino предлагает несколько бонусов, обычно на первые пять депозитов. Все ответы тут : казино с выводом. Играть в игровые автоматы на рубли получиться только после регистрации на сайте казино. Главное не забыть, что не все казино в интернете ведут честную игру и конечно же надо регистрироваться в одном из топ 10 казино. Потом далее регистрации верифицируйте свой электронный адрес и пройдите верификацию заранее чтобы потом при выводе дененг не было задержек.

26 days ago by Gewloiol

obs studio
download obs

about 1 month ago by MikeDek


https://v-mig.ru/category/poznavatelnye-stati-o-kofe/ Чтобы почувствовать прилив энергии и радости, необходимо пить кофе по утрам. Вот несколько полезных рекомендаций о том, как пить кофе по утрам:

about 1 month ago by SjrXV

I am sharing with you a site with a lot of web models that you can watch absolutely free.



The best women from the USA show their charms directly online and broadcast themselves naked.

In Girls porn cam chat big selection for every taste and color, young and old, BBW and thin, women and girls with large and small breasts.


And a real big selection of guys, shemales and couples in porn chat.
Sex chat is absolutely free, but for registration they give tokens that can be spent on gifts for girls, order a private chat, or a few minutes of virtual sex in private.

Register now: https://ustalks.com

3 months ago by LindaWhore

Several months ago I was unemployed on unemployment and struggling
Then last month I found this opportunity,
I tried it and fell in love working from home,
working my own hours and making a good living.
Fun, work, I talk on the phone and get paid,
I really want you to have a look at what I am
doing and earning

Freedom for you starts today

3 months ago by SarahAnnphoms

I am sharing with you a site with a lot of web models that you can watch absolutely free.



The best women from the United States show their charms directly online and broadcast themselves naked.

In American web cam site big selection for every taste and race, young and milf, fat and thin, women and girls with large and small breasts.


And a real big selection of guys, shemales and couples in porn chat.
Sex chat is absolutely free, but for registration they give tokens that can be spent on gifts for girls, order a private chat, or a few minutes of cyber sex in private.

Link: https://ustalks.com

3 months ago by LindaWhore

Здравствуйте, мобильная версия игры в онлайн казино Мобильная версия Joycasino мобильный игровой вариант. Игра на телефоне от Джойказино это топ. Куча моб игр для ставок на спорт , тут самые яркие выигрыши .

4 months ago by Terrydef

Как вы прогнозируете погоду?
ЛИчно я смотрю вечером на закат, но если ничего не вижу, тогда иду на сайт https://www.gismeteo.ua/ и там получаю весь прогнозируете. И было несколько раз когда сайт был не прав.
Так что доверй, но проверяй.

4 months ago by Kirilllye

Офисные АТС и IP телефония в Крыму.
Компания Tritel, участник Ассоциации Кабельных Операторов Связи Крыма, предоставляет услуги безлимитного доступа к сети Интернет для жителей Симферополя с возможностью подключения к сети на скорости 100Мбит/с.
Подключить интернет в Симферополе. Бесплатное кабельное телевидение в Симферополе. услуги безлимитного интернета всего за 360 рублей. У нас Вы можете подключить интернет всего за сутки.
Интернет провайдер в Симферополе.
Telco - Телефония в Крыму.

4 months ago by mihoDus

Nice working article!

8 months ago by FloydAmopy

Thanks!

8 months ago by Michaellache

Great Content. Works well

11 months ago by CharlesOwept

Good Read

over 1 year ago by Alvaroknogs

Thank you

over 1 year ago by ZuvilsRog

Thanks a lot for this tutorial. How can i create a separated route for the vendor, and not accessing it from the admin link? Thanks

over 3 years ago by Hugens Louis

Great Tutorial! It works!! Thanks for sharing!!!

almost 4 years ago by fhms info