I am working on the project and now I need to add a foreign key. I have these two models:class
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
My goal is print all cities, in which is the shop. I am trying to do that this way:
<% @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
I also tried to add the foreign key to the cities table:
alter table cities add foreign key (shop_sid) references shops (sid);
But got
ERROR: there is no unique constraint matching given keys for referenced table "shops"
How could I solve this problem about foreign key? Or, would be also better to update the associations?
EDIT – error message:
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
You need to specify the foreign key on each side of the relation: