malcoauri
malcoauri

Reputation: 12179

Storing array in one field Rails

There is some question: I'm making design of the database, and there is "restaurants" table; this table has field "food_type". This field may store 1 or 2, 3, ... values which are describes types of food in this restaurant (Spanish, French, Italian, etc). If I understand right I should store array of codes in this field (0=>French, 1=>Italian, ...), and I need to have table "food_types" with 'id', 'name'. But there is another problem: some of my view should show all food types, and my app uses internationalization, therefore I should store names of types in yml file for using I18n in Rails and I shouldn't use 'name' column in "food_types" instead of it. Please, tell me, what is the best solution for my problem? Thanks.

Upvotes: 0

Views: 73

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

Maybe you should introduce a has_many :through association, like this:

#app/models/restaurant.rb
has_many :restaurant_food_types
has_many :food_types, :through => :restaurant_food_types

#app/models/restaurant_food_type.rb
Class RestaurantFoodType < ActiveRecord::Base
    belongs_to :restaurant
    belongs_to :food_type
end

#app/models/food_type.rb
has_many :restaurant_food_types
has_many :restaurants, :through => :restaurant_food_types

The DB for the restaurant_food_type join model could look like this:

restaurant_food_types
  id 
  restaurant_id
  food_type_id

Upvotes: 1

Related Questions