我有两张桌子:
1.advertiser_accounts
create table if not exists advertiser_accounts (
advertiser_id int(11) not null,
deal_type_id int(11) not null,
primary key (advertiser_id),
CONSTRAINT account_advertiser_refs FOREIGN KEY (advertiser_id) REFERENCES advertisers (ap_advertiser_id ),
CONSTRAINT deal_types_refs FOREIGN KEY (deal_type_id) REFERENCES deal_types (id)
);
2。广告客户
Advertiser(id: integer, ap_advertiser_id: integer)
在模特:
的 AdvertiserAccount
class AdvertiserAccount < ActiveRecord::Base
belong_to :advertiser
end
广告客户
class Advertiser < ActiveRecord::Base
has_one :advertiser_account
end
我想将advertiser_accounts中的advertiser_id映射到广告客户表中的ap_advertiser_id
在控制台上:AdvertiserAccount.first.advertiser
AdvertiserAccount加载(0.2ms)SELECT
advertiser_accounts
。* FROMadvertiser_accounts
ORDER BYadvertiser_accounts
。advertiser_id
ASC LIMIT 1 广告客户加载(0.2ms)SELECTadvertisers
。* FROMadvertisers
WHEREadvertisers
。id
= 153371 LIMIT 1
结果我得到了
但是,我想要这样的查询:
AdvertiserAccount加载(0.2ms)SELECT
advertiser_accounts
。* FROMadvertiser_accounts
ORDER BYadvertiser_accounts
。advertiser_id
ASC LIMIT 1 广告客户加载(0.2ms)SELECTadvertisers
。* FROMadvertisers
WHEREadvertisers
。ap_advertiser_id
= 153371 LIMIT 1
答案 0 :(得分:1)
您是否检查ap_advertiser_id
是否具有唯一键约束或主键约束(如果不这样做)。
您违反了配置原则的约定,因此您必须在模型中明确指定主键和外键。
尝试将模型更改为 -
class AdvertiserAccount < ActiveRecord::Base
belong_to :advertiser, :foreign_key => :ap_advertiser_id, :primary_key => :advertiser_id
end
class Advertiser < ActiveRecord::Base
has_one :advertiser_account, :primary_key => :ap_advertiser_id, :foreign_key => :advertiser_id
end