2015-04-02 42 views
0

我一直在試圖讓rolify寶石FOREVER工作聯繫起來。我有cancancan和設計,我基本上有一個註冊頁面的電子郵件,密碼,password_confirmation,和一個下拉框選擇角色。當我點擊註冊時,它會給創建DDbox的代碼段提供一個錯誤。任何人都可以幫助我做到這一點?我ability.rb是這個如何將角色從一個下拉框,用戶使用rolify

`類能力 包括慘慘::能力

高清初始化(用戶) 用戶|| = User.new 如果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 ` 

,並從我的觀點這個下拉框中的代碼片段/設計/ 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` 

回答

0

User.new不保存記錄,因此不會有一個id。

嘗試保存要麼user.save或使用User.create代替它添加角色之前的ID的用戶。否則角色將不會有一個user_id用於關聯。

user = User.create(:email => '[email protected]', :password => 'somestring', :password_confirmation => 'somestring') 

user.add_role :rolename 
相關問題