首先,对我来说,如果使用string列只存储两种类型的内容,这看起来不太好。当有更多类型的食物时,可以将其存储为布尔值或整数。您可以添加一个数组,该数组将膳食类型id映射到
lunch
或
dinner
或者别的什么。
# Ingredient model
belongs_to :dish
def meal
MEAL_TYPES[meal_id]
end
private
MEAL_TYPES = ['lunch', 'dinner']
# Dish model
has_one :lunch, :class_name => 'Ingredient', :conditions => {:meal_id => 0}
has_one :dinner, :class_name => 'Ingredient', :conditions => {:meal_id => 1}
然后在代码中,您可以将其用作休耕地:
@dish = Dish.find(params[:id])
@dish.lunch # returns lunch ingredients
@dish.dinner # returns dinner ingredients
@dish.lunch.meal # => "lunch"