Adding Role dynamically through Form USing Rolify along with Devise and Cancan

无人久伴 提交于 2019-12-13 02:12:42

问题


I just followed the tutorial "https://github.com/EppO/rolify/wiki/Tutorial" its very nice and working fine. But my question can't we add Role through form with out using Rails console.

<div class="field"><%= user_form.label :email %><br />
<%= user_form.email_field :email %></div>
<div class="field"><%= user_form.label :password %><br />
<%= user_form.password_field :password %></div>
<div class="field"><%= user_form.label :password_confirmation %><br />
<%= user_form.password_field :password_confirmation %></div>
<div class="field">
  <%= f.label :roles %>
  <div class="controls">
    <% Role.all.each do |role| %>
      <%= check_box_tag "user[role_ids][]", role.id, @user.role_ids.include?(role.id) %>
      <%= role.name %><br />
    <% end %>
  </div>
</div>
<% end %>

The Role column connect to roles table (Rolify Roles)

Here is my role.rb

class Role < ActiveRecord::Base

has_and_belongs_to_many :users, :join_table => :users_roles

belongs_to :resource, :polymorphic => true

User.rb

class User < ActiveRecord::Base

belongs_to :account, :inverse_of => :users

validates :account, :presence => true

rolify

attr_accessible :role_ids

# Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable

devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model

attr_accessible :email, :password, :password_confirmation, :remember_me, :role_ids

# attr_accessible :title, :body

has_many :auditinits

end

Any help is appreciate!!


回答1:


In User Form, make a Drop down select for the roles as,

<%= user_form.select :role,options_from_collection_for_select(Role.all,"name","name) %>

Modify Create action in Users Controller as

@user = User.new(user_params)

@user.add_role params[:user][:role]


来源:https://stackoverflow.com/questions/23055872/adding-role-dynamically-through-form-using-rolify-along-with-devise-and-cancan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!