ruby on rails - How to store City and Neighborhood associated with a Restaurant? -


i have list of restaurants. each 1 located in neighborhood/district, in particular city.

how relate restaurants both neighborhood , city? want do:

restaurant (belongs_to) -> neighborhood restaurant (belongs_to) -> city 

or

restaurant (belongs_to) -> neighborhood neighborhood (belongs_to) -> city 

what advantage or disadvantage of taking 1 or other approach, , should choose?

thanks

the relationships

the second set of relationships appropriate. primary reason, mik_die mentioned, is normalized. if @ db schema first example have following

restaurant (belongs_to) -> neighborhood restaurant (belongs_to) -> city  table: restaurant column          |  type       |  --------------------------------------------- id              |  integer    |  primary key name            |  string     | neighborhood_id |  integer    |  foreign key city_id*        |  integer    |  foreign key  table: neighborhood  column          |  type       |  --------------------------------------------- id              |  integer    |  primary key name            |  string     | city_id*        |  integer    |  foreign key  table: city  column          |  type       |  --------------------------------------------- id              |  integer    |  primary key name            |  string     | 

if @ columns put asterisk beside see duplicated in 2 different tables, want avoid while normalizing database.

the second schema going identical. remove city_id column restaurant.

restaurant (belongs_to) -> neighborhood neighborhood (belongs_to) -> city  table: restaurant column          |  type       |  --------------------------------------------- id              |  integer    |  primary key name            |  string     | neighborhood_id |  integer    |  foreign key 

where rails comes in

your post tagged ruby on rails, think important discuss how rails views relationship. familiar belongs_to , has_many associations. rails provides excellent extension has_many :through option.

i'm going assume interested in storing city in restaurant table since want able find restaurants belong whole city. :through option of has_many allows functionality.

your models this

class restaurant < activerecord::base   belongs_to :neighborhood end  class neighborhood < activerecord::base   has_many :restaurants   belongs_to :city end  class city < activerecord::base   has_many :neighborhoods   has_many :restaurants, through: :neighborhoods end 

you this

@neighborhood.restaurants # => returns restaurants neighborhood @city.restaurants # => returns restaurants each of neighborhoods belonging city 

Comments