在Ruby on Rails中遇到这种1:1关联的问题

时间:2014-12-08 17:12:22

标签: ruby-on-rails

我遇到了这种简单关联的问题(一对一关联:每个只有一个角色);我无法真正看到问题所在: 谢谢你的时间!

这是我的架构:

 create_table "roles", force: true do |t|
    t.string  "description"
    t.string  "name"
    t.integer "user_id"
  end

  create_table "users", force: true do |t|
    t.string  "name"
    t.string  "email"
    t.string  "password_digest"
    t.integer "tel"
  end

我的模特:

class Role < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :role
end

这是我的错误:

 :001 > u = User.first
  User Load (0.1ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" ASC LIMIT 1
 => #<User id: 1, name: "fer", email: nil, password_digest: nil, tel: nil>
 :002 > r = Role.first
  Role Load (0.1ms)  SELECT  "roles".* FROM "roles"   ORDER BY "roles"."id" ASC LIMIT 1
 => #<Role id: 1, description: nil, name: "simple_user", user_id: nil>
 :003 > u.role << r
  Role Load (0.2ms)  SELECT  "roles".* FROM "roles"  WHERE "roles"."user_id" = ? LIMIT 1  [["user_id", 1]]
NoMethodError: undefined method `<<' for nil:NilClass
    from (irb):3

2 个答案:

答案 0 :(得分:0)

所以我只是猜测你的问题是什么,因为你没有真正解释你遇到的问题,但看起来你没有在你的问题中定义外键。架构,因此您的数据库不知道如何查找关联。我会像这样重写你的迁移:

create_table "users", force: true do |t|
  t.string  "name"
  t.string  "email"
  t.string  "password_digest"
  t.integer "tel"
end

create_table "roles", force: true do |t|
  t.string  "description"
  t.string  "name"
  t.references :user
end

execute <<-SQL
  ALTER TABLE roles
    ADD CONSTRAINT fk_roles_users
    FOREIGN KEY (user_id)
    REFERENCES users(id)
SQL

答案 1 :(得分:0)

因为它是一个has_one,你不能<<,你会做=。这样做将是数据库更新(设置主键和外键并保存)