2012-03-23 12 views
0

私はプロジェクトに取り組んでいますが、今は外部キーを追加する必要があります。私はこれらの2つのモデルを持っています:クラス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" 

を得ました外部キーに関する問題?あるいは、協会を更新する方が良いでしょうか?

EDIT - エラーメッセージ:

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 

答えて

2

あなたは関係の各側に外部キーを指定する必要があります。

class Shop < ActiveRecord::Base 
    belongs_to :owner 
    has_many :cities, :foreign_key => 'shop_sid' 
end 

class City < ActiveRecord::Base 
    belongs_to :shop, :foreign_key => 'shop_sid' 
end 
+0

私は関係の両側に外部キーを追加し、古いエラーがなくなり、私はこれを得ました(更新されたオリジナルの投稿)。 '' shop_sid "= 1034'という部分は' 'shop_id''列の値を' '1034''という値で表しているのでかなり間違っています。私はまだ何が欠けていますか? – user984621

+0

@ user984621 - あなたの 'shop_sid'フィールドが' varchar'であるというエラーが表示されています。私は 'shop_id'カラムについてのあなたの言及も混乱しています。データベーススキーマを投稿する可能性がありますか? – Chowlett

関連する問題