[英]How do you automatically add foreign keys to an existing Rails database?
[英]In Rails, how do you add multiple foreign keys to the same model? I have the Django equivalent
我正在使用Rails 3 Beta,并且我认为语法类似于2.x。 我对Ruby和Rails也不太熟悉。
在Django中,指向同一模型的多个外键如下所示:
class Dish(models.Model):
name = models.CharField(max_length=100)
lunch = models.ForeignKey(Ingredient, related_name='lunch')
dinner = models.ForeignKey(Ingredient, related_name='dinner')
class Ingredient(models.Model):
spices = models.IntegerField()
veggies = models.IntegerField()
在Rails中,我正在考虑执行以下操作:
# Migration file
create_table :dishes do |t|
t.column :name, :string
end
create_table :ingredients do |t|
t.column :spice, :integer
t.column :veggies, :integer
t.column: :dish_id, :integer
t.column: :meal, :string # lunch or dinner
end
# Models
class Dish < ActiveRecord::Base
def lunch
return # ingredient for the current dish where type == lunch
end
def dinner
return # ingredient for the current dish where type == dinner
end
end
以上是正确的想法还是有更好的方法呢?
更多说明:该餐厅在午餐和晚餐时段提供相同的菜肴,但在这两次用餐之间使用的食材数量不同。 每道菜最多可以包含一个午餐成分对象和最多一个晚餐成分对象。
从您的模型尚不清楚, Dish
模型和Ingredients
模型之间是否存在1-to-1
或1-to-n
关系。 如果关系是1-to-1
,则以下代码应该起作用:
class Dish < ActiveRecord::Base
has_one :lunch, :class_name => 'Ingredient', :conditions => {:meal => 'lunch'}
has_one :dinnner, :class_name => 'Ingredient', :conditions => {:meal => 'dinner'}
end
# now you can get lunch and dinner using the calls below on a Dish object.
dish.lunch
dish.lunch
如果该关系是1-to-n
,则以下代码应工作:
class Dish < ActiveRecord::Base
has_many :lunches, :class_name => 'Ingredient', :conditions => {:meal => 'lunch'}
has_many :dinnners, :class_name => 'Ingredient', :conditions => {:meal => 'dinner'}
end
首先,对我而言,如果您使用字符串列仅存储两种类型的内容,则效果并不理想。 当膳食种类更多时,可以将其存储为布尔值或整数。 您可以添加一个将膳食类型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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.