![](/img/trans.png)
[英]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.