Gareth Jones
Gareth Jones

Reputation: 1810

Linking/Connecting two db rows in Rails

I'm trying to find a way of connecting two active record objects, not a full merge but somehow having them associated.

For example if I had two models, City and Restaurant, each city can have many restaurants. In this example if there are two City records, "Napoli" and "Naples" that represent the same city, I would like to connect them in the db so regardless of whether the user clicked on restaurants in "Napoli" or "Naples" they would be taken to the same page.

I apologize if I've explained this poorly, I can't fully articulate what I'm after without using an example.

I'm using Rails 3.2, ruby 1.9.2 and postgres

Thanks.

Upvotes: 0

Views: 36

Answers (2)

Sean Xiao
Sean Xiao

Reputation: 616

class City < ActiveRecord::Base
  has_many :city_name, :dependent => :destroy
end

class CityName < ActiveRecord::Base
  belongs_to :city
end

When you search for a city in your controller, you can check all the names and if any matches you render the same restaurant.

Upvotes: 1

Dhaivat Pandya
Dhaivat Pandya

Reputation: 6536

You can add a lookup field that two cities that are actually the same have in common (kind of ad-hoc solution, but, I think it works).

So, Napoli and Naples would have maybe a "City id" of 46, whereas "Mumbai" and "Bombay" would have a city id of 32.

Upvotes: 0

Related Questions