1

すべてのユーザーに複数のロールを割り当てて、User.first.roles のようなものでそれらを元に戻せるようにしたいのですが、道に迷ってしまいました。Rails コンソールを使用してどうすればよいでしょうか? モデルで何が間違っていますか?

u = User.first

User Load (0.1ms)  SELECT "users".* FROM "users" LIMIT 1
 => #<User id: 18 [...]>

1.9.3-p194 :004 > u.roles
NameError: uninitialized constant User::Assignment
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/inheritance.rb:119:in `compute_type'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/reflection.rb:172:in `klass'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/reflection.rb:385:in `block in source_reflection'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/reflection.rb:385:in `collect'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/reflection.rb:385:in `source_reflection'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/reflection.rb:508:in `check_validity!'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/associations/association.rb:26:in `initialize'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/associations/collection_association.rb:24:in `initialize'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/associations/has_many_through_association.rb:10:in `initialize'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/associations.rb:157:in `new'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/associations.rb:157:in `association'
    from [path]/ruby-1.9.3-p194/gems/activerecord-3.2.3/lib/active_record/associations/builder/association.rb:44:in `block in define_readers'
    from (irb):4
    from [path]/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
    from [path]/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
    from [path]/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

models/user.rb

class User < ActiveRecord::Base
 attr_accessible :name, :email, :password, :password_confirmation, :role_id
 has_many :assignments
 has_many :roles, through: :assignments
 #more code...
end

models/role.rb

class Role < ActiveRecord::Base
 attr_accessible :name
 has_many :assignments
 has_many :users, through: :assignments
end

models/assignments.rb

class Assignments < ActiveRecord::Base
 attr_accessible :role_id, :user_id
 belongs_to :user
 belongs_to :role
end

schema.rb: http://cl.ly/323n1t0Q1t390y1M2S0E

4

1 に答える 1

3

モデル ファイルの名前をmodels/assignments.rbmodels/assignment.rb、そのクラス名を からclass Assignmentsに変更しclass Assignmentます。モデル名は、Rails の慣例に従って単数形にする必要があります。したがって、実行u.rolesすると、割り当てではなく割り当てが検索されます。

于 2012-07-10T03:28:12.910 に答える