Active Record关联链接,但无法分配值

时间:2015-06-22 13:02:36

标签: ruby-on-rails

我正在为每个用户设置权限,以确定他们对某些数据的访问权限。我有一个a1, a2, a3模型和一个p1, n2, c3模型,该模型设置了userpermission关联,如下所示:

应用/模型/ permission.rb

has_many

应用/模型/ user.rb

belongs_to

我用来设置此表的迁移如下:

分贝/迁移/ create_permissions.rb

class Permission < ActiveRecord::Base
  has_many :users
end

当我进入Rails控制台时出现问题。示例会话可能如下所示:

class User < ActiveRecord::Base
  belongs_to :permission
end

class CreatePermissions < ActiveRecord::Migration def change create_table :permissions do |t| t.string :group t.string :can_see t.string :cant_see t.timestamps null: false end add_column :users, :permissions_id, :integer end end 之类的命令会返回值,该值应该是irb(main):001:0> User.column_names => ["id", "name", "email", "created_at", "updated_at", "password_digest", "remember_digest", "admin", "activation_digest", "activated", "activated_at", "reset_digest", "reset_sent_at", "last_active_at", "permissions_id"] irb(main):002:0> User.first.permissions_id User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 => 3 irb(main):003:0> User.first.permission User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 => nil irb(main):004:0> Permission.where(id: 3) Permission Load (0.3ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."id" = ? [["id", 3]] => #<ActiveRecord::Relation [#<Permission id: 3, group: "CA", can_see: "Some stuff", cant_see: "Some stuff", created_at: "2015-06-22 12:28:55", updated_at: "2015-06-22 12:28:55">]> irb(main):005:0> User.first.permission.group User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 NoMethodError: undefined method `group' for nil:NilClass 模型的外键,但运行User.first.permissions_id会返回Permission

1 个答案:

答案 0 :(得分:3)

您的列应为permission_id,而不是permissions_id。这就是AR找不到相关模型的原因。