PostgreSQL, Rails 3 - как добавить новый внешний ключ в ассоциации? - PullRequest
0 голосов
/ 23 марта 2012

Я работаю над проектом, и теперь мне нужно добавить внешний ключ. У меня есть эти две модели: класс

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

1 Ответ

2 голосов
/ 23 марта 2012

Необходимо указать внешний ключ на каждой стороне отношения:

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
...