0

Am building a rails app where i want to have two types of users i.e sellers and buyers. Users can choose at the time of signup weather they want to signup as seller or buyer.

I created users using devise then added enum role: [:seller, :buyer] in user.rb

then created a migration to add roles to user

rails g migration add_role_to_users

my migration looks like this:

class AddRoleToUsers < ActiveRecord::Migration
   def change
      add_column :users, :role, :integer
   end
end

I am using simple form, in my users registration form i added

<%= f.select :role, User.roles %>

On the index page i am trying to do this:

<% if current_user.seller? %>
  <%= link_to 'New Post', new_post_path %>
  <% else %>
  hello
<% end %>

but somehow roles of my users is returning as nil, i have checked the console also and even there the roles of my user return as nil, can someone please help me and tell me what am doing wrong. Thanking you

That dude
  • 379
  • 1
  • 4
  • 17

1 Answers1

0

Your code looks fine, assuming you ran rake db:migrate. In the console the role of any particular user returns nil because you have not yet saved a role for any of them (for instance you must get nil when you type User.last.role in the console). But if you type User.last.update_attributes(role: 1), then in the output of User.last you should see that his role has been modified and is now buyer. If it is not the case, please share the error you get. To get it work at signup, you must configure your registration controller properly, in order to allow Devise to use the new parameter. You can find all info in this post. In short you can do it in three steps:

1/ In your file route.rb:

devise_for :users, controllers: {
       :registrations => "users/registrations" }

2/ In your registration controller:

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  # GET /resource/sign_up
  def new
    super
  end
  #then the method called in the before action where you permit the parameters
  protected
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :birth_date, :role, :otherkeysyouneed])
  end
end

3/ in your registration view

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= f.select :role, User.roles %>

And you should be sorted. Good luck and refer the above linked post and the Devise documentation, more info in there if you need.

Guillaume Bihet
  • 625
  • 1
  • 9
  • 17
  • thanks @Guilliaume Bihet yeah it works, but i want to know why it's not assigning roles to users when they choose at the time of signup, and how can i do that? – That dude Feb 15 '19 at 10:39
  • 1
    you're welcome @Thatdude, I updated my post with some further info as it seems the part you are missing is adding extra parameters to Devise at signup to get it work fully. – Guillaume Bihet Feb 15 '19 at 13:51