1

私がやろうとしているのは、すべてのユーザーの役割を「ユーザー」に設定することですが、コンソールやRubyはあまり使用していません。これは、以下の使用方法から明らかです。

私はこのようなものがうまくいくことを望んでいました:

u=User.all
u.role.name="user"

しかし、明らかに、それは機能しておらず、どのように進めるかがわかりません。

能力モデルでCanCanを使用しており、役割の「名前」列で役割名を設定しています。ユーザーは割り当てを通じて多くの役割を果たします

user.rb

has_many :assignments
has_many :roles, :through => :assignments

すべての設定方法は次のとおりです。

Assignment.rb

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # in case of guest
    if user.has_role? :admin
      can :manage, :all
    #else
     # can :read, :all
  end
  end
end

role.rb

class Role < ActiveRecord::Base
  attr_accessible :name
  has_and_belongs_to_many :users, :join_table => :users_roles
  belongs_to :resource, :polymorphic => true
end

役割スキーマ

  # == Schema Information
  #
  # Table name: roles
  #
  #  id            :integer         not null, primary key
  #  name          :string(255)
  #  resource_id   :integer
  #  resource_type :string(255)
  #  created_at    :datetime        not null
  #  updated_at    :datetime        not null
  #

コンソールを使用するすべてのユーザーの役割名を設定する方法を教えてください。

4

1 に答える 1

2

使用update_all

role = Role.find_by_name 'user'
User.update_all :role => role

ただし、update_allActiveRecordコールバックはトリガーされないため、それらが必要な場合は、代わりにすべてのユーザーを反復処理する必要があります。

role = Role.find_by_name 'user'
User.find_each do |user|
  user.role = role
  user.save
end

User.find_each1000人を超えるユーザーがいる場合は、メモリ使用量を最小限に抑えるためにユーザーをバッチでロードします。

于 2012-11-11T18:09:38.997 に答える