Domanda

Let's say a "user" wants to specify their favorite "cities". What is the correct way to model this relationship?

Option 1

Associations:

User has_many :cities through :city_preferences. 
CityPreferences belongs_to :user and :city. 
City has_many :users through :city_prefences.

Tables:

User
email:string, first_name:string, last_name:string

CityPreferences
user:references, city:references

City
name:string

Option 2

Associations:

User has_many :city_preferences
CityPreferences belongs_to :user

Tables:

User 
email:string, first_name:string, last_name:string

CityPreferences
user:references city:string
È stato utile?

Soluzione

You can easily achieve that with the help of the has_many :sm, through: :relation:

class User < ActiveRecord::Base
  has_many :user_city_relations
  has_many :preferred_cities, through: :user_city_relations, source: :city

class City < ActiveRecord::Base
  has_many :user_city_relations
  has_many :users, through: :user_city_relations

class UserCityRelation < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
  validates :user_id, :city_id, presence: true

And use it like this:

user.preferred_cities

It is very similar to a has_and_belongs_to_many but here you define the join model by yourself, which gives you more control about this relation. It is also more flexible (for new features in the futures, like active/inactive preferred Cities, etc.)

Altri suggerimenti

If I understand your question, you're not asking how to implement option 1 or 2, but which of option 1 or option 2 is preferred.

That depends on your application and whether you want each city to exist and be managed as a separate object.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top