i can't seem figure out how match more 1 string column foreign key. have 2 models. shop , neighborhood. both have city , state column.
how can set association multiple foreign key string? right neighborhood of vancouver, bc show shops vancouver, bc , vancouver, wa.
shop - id - city (string) - state (string) - country (string) belongs_to :neighborhood, foreign_key: :city, primary_key: :city neighborhood - id - city (string) - state (string) - country (string) has_many :shops, foreign_key: :city, primary_key: :city
your pattern improved.
you're referencing "foreign_key
" string... should integer
. if refactor pattern, issue go away completely...
#app/models/shop.rb class shop < activerecord::base # id | city_id | ... belongs_to :city end #app/models/city.rb class city < activerecord::base has_many :shops belongs_to :state #-> can removed end #app/models/state.rb class state < activerecord::base belongs_to :country #-> can removed end
by nature, foreign_key
has identify primary_key
(unique_key
) of associative table:
in context of relational databases, foreign key field (or collection of fields) in 1 table uniquely identifies row of table
this means if you're referencing city, should not matter if "name" of city same... if other table contains appropriate data (ie city
uniquely located within state
etc).
--
i recommend refactoring models shop belongs_to city
. you'd able associate each city
respective states
etc.
instead of including state
& country
model, use countries
gem, includes references various countries in world, , states.
Comments
Post a Comment