简体   繁体   中英

Rails join(includes) tables where “id” is not present in one table and different primary key

I have two models where one has "id" as the primary key. Second model doesn't have "id" as primary key. Instead has a composite key. How to join these?

class A < ActiveRecord::Base
  has_one :B, :order => "dt DESC"
end

class B < ActiveRecord::Base
  belongs_to :A, :foreign_key => :emp_id
end

The emp_id acts as the foreign key. In the controller for A,

arel = A.includes(:b)

This fails. I get following error,

ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'b.id' in 'field list': SELECT a . id AS t0_r0,....

How shall I proceed?

Try setting the primary_key on the belongs_to or the has_one .

More info on these options can be found at,

ActiveRecord belongs_to

ActiveRecord has_one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM