【发布时间】:2012-09-28 14:36:20
【问题描述】:
我想做一个烹饪网站,但不知道正确的方法是建立数据库。
我的模型是:Recipe 和 Ingredient。
配方中的成分应为自动完成字段。问题是用户可以在那里放置任何文本。 (“黄瓜”或“黄瓜”),它会是不同的成分。
我想按成分和指向它们的链接进行搜索。最好的方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby database
我想做一个烹饪网站,但不知道正确的方法是建立数据库。
我的模型是:Recipe 和 Ingredient。
配方中的成分应为自动完成字段。问题是用户可以在那里放置任何文本。 (“黄瓜”或“黄瓜”),它会是不同的成分。
我想按成分和指向它们的链接进行搜索。最好的方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby database
一个食谱有很多项目,这些项目又保留了对成分、数量和度量类型的引用。所以你可以去:
rails generate model Recipe name:string description:text
rails generate model Item recipe:references ingredient:references amount:decimal measure:string
rails generate model Ingredient name:string
然后添加到你的类中:
class Recipe < ActiveRecord::Base
has_many :items
has_many :ingredients, :through => :items
# this allows things like @recipes = Recipe.using("cucumber")
scope :using, lambda do |text|
joins(:ingredients).where("ingredients.name LIKE ?", "%#{text}%")
end
end
class Item < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
VALID_MEASURES = %w[oz kg tbsp] # use for "select" tags in forms
validates :measure, :inclusion => VALID_MEASURES
end
class Ingredient < ActiveRecord::Base
belongs_to :item
end
您可以从这里开始构建您的视图,自动完成,无论您的想象力是否允许。
【讨论】: