0
我正在研究这个项目,现在我需要添加一个外键。我有这两种模式:类PostgreSQL,Rails 3 - 如何在关联中添加新的外键?
class Owner < ActiveRecord::Base
has_many :shops
end
class Shop < ActiveRecord::Base
belongs_to :owner
has_many :cities
end
class City < ActiveRecord::Base
belongs_to :shop, :foreign_key => 'shop_sid'
end
我的目标是打印所有的城市,其中是商店。我试图做的是这样的:
<% @owner.shops.each do |shop| %>
<% shop.cities.each do |city| %>
<%=city.position%><br />
<%end%>
<%end>
But I am getting the error
PG::Error: ERROR: column cities.shop_id does not exist
LINE 1: ...T "cities".* FROM "cities" WHERE "cities...
^
: SELECT "cities".* FROM "cities" WHERE "cities"."shop_id" = 8
我也试图与外键添加到cities
表:
alter table cities add foreign key (shop_sid) references shops (sid);
,但得到
ERROR: there is no unique constraint matching given keys for referenced table "shops"
我怎么能解决这个问题关于外键的问题?或者,更新协会也会更好?
PG::Error: ERROR: operator does not exist: character varying = integer
LINE 1: ...ons" WHERE "cities"."shop_sid" = 1034
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "cities".* FROM "cities" WHERE "cities"."shop_sid" = 1034
我加入了外键关系的双方,旧的错误消失了,我得到了这个(更新的原始帖子)。奇怪的是 - “城市”的部分。“shop_sid”= 1034'是非常错误的,因为值“1034”是来自'shop_id'列的值。我错过了什么? – user984621 2012-03-23 13:18:46
@ user984621 - 该错误似乎表明您的'shop_sid'字段是'varchar'。我也对你提到的'shop_id'列感到困惑。也许你可以发布你的数据库模式? – Chowlett 2012-03-23 13:48:10