【问题标题】:Rails broken association with custom idsRails 与自定义 ID 的关联中断
【发布时间】:2014-04-23 13:28:32
【问题描述】:

当我使用自定义外键执行关系时,rails 不会将 id 传递给查询,而是传递 [[nil, nil]]:

jruby-1.7.11 :081 > u.user_privileges
UserPrivilege Load (61.0ms)  
SELECT "A_USERPRIVILEGES".* FROM "A_USERPRIVILEGES"  
WHERE "A_USERPRIVILEGES"."ID_A_USERS" = :a1  [[nil, nil]]  =>
#<ActiveRecord::Associations::CollectionProxy []>

我有 rails 4.1、jruby-1.7.11、oracle_enhanced 适配器和 oracle 11g db

这是我的代码:

class User < ActiveRecord::Base
  self.table_name = 'A_USERS'
  self.primary_key = 'ID'

  has_many :user_privileges, foreign_key: 'ID_A_USERS', 
    primary_key: 'ID' # when i remove primary key here then nothing changing
end

class UserPrivilege < ActiveRecord::Base
  self.table_name = 'A_USERPRIVILEGES'
  self.primary_key = 'ID'

  belongs_to :user, foreign_key: 'ID_A_USERS', 
    primary_key: 'ID' # when i remove primary key here then nothing changing

  alias_attribute :user_id, :id_a_users # does not work too
end

表格信息:

  A_USERS:
    ID  NUMBER(38,0)

  A_USERPRIVILEGES:
    ID     NUMBER(38,0)
    ID_A_USERS NUMBER(38,0)

更新

我只是用 mysql 数据库创建了测试项目,其代码和架构与上面写的完全相同,它正在工作......

oracle 的问题仍未解决。

【问题讨论】:

    标签: ruby-on-rails ruby oracle activerecord associations


    【解决方案1】:

    你试过了吗

    class User < ActiveRecord::Base
      self.table_name = 'A_USERS'
      self.primary_key = 'ID'
    
      has_many :user_privileges, class_name: 'UserPrivilege', foreign_key: 'ID_A_USERS'
    end
    
    class UserPrivilege < ActiveRecord::Base
      self.table_name = 'A_USERPRIVILEGES'
      self.primary_key = 'ID'
    
      belongs_to :user, class_name:'User', foreign_key: 'ID', primary_key: 'ID_A_USER'
    end
    

    foreign_key 是另一个表中的键,primary_key 是当前表中的键,所以这是说在 A_USERS.ID 中查找 ID_A_USER

    另外,在做这样的自定义表格时,我总是喜欢告诉它,Association 类可能是多余的,但对我来说似乎很有用。

    也请不要来自here

    添加了 emulate_integers_by_column_name 选项 设置下面的选项,结果列末尾带有 ID 的列将始终模拟为 Fixnum(如果在旧数据库中将列类型指定为 NUMBER 而没有精度信息,默认情况下映射到 BigDecimal Ruby 类型,则很有用)

    ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_integers_by_column_name = true
    

    【讨论】:

    • 问题依旧,没有任何改变。
    猜你喜欢
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多