首页 文章

如何使用rolify将角色从下拉框关联到用户

提问于
浏览
1

我一直试图让rolify gem永远工作 . 我有cancancan和设计,我基本上有一个注册页面,其中包含电子邮件,密码,password_confirmation和下拉框选择角色 . 当我点击注册时,它给我一个创建DDbox的代码段的错误 . 任何人都可以帮我搞定这个吗?我的能力.rb就是这个

`class能力包括CanCan :: Ability

def initialize(user)user || = User.new if user.has_role? :admin可以:管理,:所有elsif user.has_role? :regularUser可以:读取,菜单elsif user.has_role? :机构可以:阅读,菜单elsif user.has_role? :franchiseOwner可以:阅读,菜单
结束

# Define abilities for the passed in user here. For example:
#
#   user ||= User.new # guest user (not logged in)
#   if user.admin?
#     can :manage, :all
#   else
#     can :read, :all
#   end
#
# The first argument to `can` is the action you are giving the user
# permission to do.
# If you pass :manage it will apply to every action. Other common actions
# here are :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on.
# If you pass :all it will apply to every resource. Otherwise pass a Ruby
# class of the resource.
#
# The third argument is an optional hash of conditions to further filter the
# objects.
# For example, here the user can only update published articles.
#
#   can :update, Article, :published => true
#
# See the wiki for details:
# https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities
end
 end `

这是我的视图/ devise / registation / new.html.erb中的下拉框代码片段..
<%= user_form.select :role, options_from_collection_for_select(Role.all,"Institution","Regular User", "Franchise Owner")%>

这是我的User.rb模型

`class User < ActiveRecord::Base
 rolify :before_add => :before_add_method

 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable and :omniauthable
 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

 def before_add_method(role)

 end
 end`

和我的users_controller

`class UserController < ApplicationController
 def index
  @users = User.all
 end

 def new
   @user = User.new
 end


 # POST /userss
 # POST /users.json
 def create
 @user = User.new(user_params)
 @user.add_role params[:user][:role]
 end

 private
 def user_params
params.require(:user).permit(:email, :password, :password_confirmation,    :role)
end
end`

1 回答

  • 0

    User.new不保存记录,因此不会有id .

    尝试使用user.save或使用User.create保存用户,以便在添加角色之前具有id . 否则,角色将没有user_id用于它的关联 .

    user = User.create(:email => 'foo@bar.com', :password => 'somestring', :password_confirmation => 'somestring')
    
    user.add_role :rolename
    

相关问题