当前位置:  开发笔记 > 编程语言 > 正文

Rails字符串作为外键

如何解决《Rails字符串作为外键》经验,为你挑选了1个好方法。

UserCourse(典型的注册数据)之间有关系.A User has_many Course,反之亦然(典型JOIN表格方案).

我试图has_and_belongs_to_many将这两个模型之间的关系迁移到has_many :through关系中.我的文件目前看起来像:

class User < ActiveRecord::Base

    has_and_belongs_to_many :courses
end

class Course < ActiveRecord::Base

    has_and_belongs_to_many :users
end

和连接两个模型的表名是courses_users.

我现在需要将此关系迁移到has_many :through关联,并且还要使列类型为user_ida string,因为我想使用g_number(字符串)属性User作为外键.注意:我不关心int和之间的性能差异varchar/string.

简短的问题是我需要users.g_number引用enrollments.user_id外键,两者都是字符串.

我尝试迁移和模型返工是这样的:

class User < ActiveRecord::Base

    has_many :enrollment
    has_many :courses, :through => :enrollment
end

class Course < ActiveRecord::Base

    has_many :enrollment
    has_many :users, :through => :enrollment
end

最后

class Enrollment < ActiveRecord::Base

    belongs_to :course
    belongs_to :user
end

那么迁移

class ChangeUserIdJoin < ActiveRecord::Migration
    def self.up
        rename_table :courses_users, :enrollments
    end

    def self.down
        rename_table :enrollments, :courses_users
    end
end

这里一切都很好.我可以做User.courses和的查询Course.users.但是现在我想user_id将连接表中列的类型更改为a,string以便我可以存储g_number(字符串属性User)并连接到字符串而不是串行idUser.

当我尝试将user_id列类型更改string为迁移时:

class ChangeUserIdJoin < ActiveRecord::Migration
    def self.up
        change_column :courses_users, :user_id, :string
        rename_table :courses_users, :enrollments
    end

    def self.down
        rename_table :enrollments, :courses_users
        change_column :courses_users, :user_id, :integer
    end
end

查询Course.usersUser.courses开始失败(下面是Rails控制台).User.courses返回一个空数组(而在有多个Course对象之前),并Course.users因为列类型不匹配而引发异常(这显然是有意义的):

u = User.take
  User Load (0.9ms)  SELECT  "users".* FROM "users"  LIMIT 1
 => # 
2.1.5 :002 > u.courses
  Course Load (0.9ms)  SELECT "courses".* FROM "courses" INNER JOIN "enrollments  ON "courses"."id" = "enrollments"."course_id" WHERE "enrollments"."user_id" = $1  [["user_id", 1]]
 => # 
2.1.5 :003 > c = Course.take
  Course Load (0.7ms)  SELECT  "courses".* FROM "courses"  LIMIT 1
 => # 
2.1.5 :004 > c.users
PG::UndefinedFunction: ERROR:  operator does not exist: integer = character varying
LINE 1: ... "users" INNER JOIN "enrollments" ON "users"."id" = "enrollm...

我需要能够加入enrollments.user_id = users.g_number.我需要做什么才能将user_id列更改为模型/表中的string类型Enrollment,并且仍然可以执行User.coursesCourse.users?之类的Active Record查询?



1> rohan..:

尝试在注册模型中指定外键和主键,如下所示

belongs_to :user foreign_key: :user_id, primary_key: :g_number

推荐阅读
凹凸曼00威威_694
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有