Rails破坏了与自定义ID的关联

时间:2014-04-23 13:28:33

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

当我使用自定义外键执行关系时,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 adapter和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的问题仍然没有解决。

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

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是当前表的关键,所以这就是在ID_A_USER中寻找A_USERS.ID

同样在做这样的自定义表时,我总是想告诉它,Asssociation类可能是多余的,但对我来说似乎很有用。

另请注意here

  

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

ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_integers_by_column_name = true