我是Sinatra的新手,我遇到了DataMapper一对多关系的问题
db.rb
env = ENV["RACK_ENV"]
url = Dir.pwd + "/db/#{env}"
DataMapper.setup :default, "sqlite://#{url}.sqlite3"
class Order
include DataMapper::Resource
property :id, Serial
property :client, String
has n, :order_items
end
class OrderItem
include DataMapper::Resource
property :id, Serial
property :dish_id, Integer
belongs_to :order
end
DataMapper.finalize
DataMapper.auto_upgrade!
dishes.rb
DISHES = [
{ id: 1, name: "Mac and Cheese", category: "Pasta", price: 10 },
{ id: 2, name: "Steak", category: "Meat", price: 9 },
{ id: 3, name: "Fish and Chips", category: "Fish", price: 12 },
{ id: 4, name: "Tiramisu", category: "Dessert", price: 5 }
]
app.rb
get do
@orders = Order.all
@dishes = DISHES
haml %s(orders/index)
end
index.haml
%table.row
-@orders.each do |order|
%tr
%td=order.client
%td
%ul
-order.order_items.each do |item|
%li
-@dishes.select { |dish| dish[:id] == item.dish_id }.first[:name]
这一行:
-@dishes.select { |dish| dish[:id] == item.dish_id }.first[:name]
没有显示客户已经挑选的任何菜肴,出了什么问题?
答案 0 :(得分:0)
对不起我是傻瓜,这一行:
-@dishes.select { |dish| dish[:id] == item.dish_id }.first[:name]
应该是:
=@dishes.select { |dish| dish[:id] == item.dish_id }.first[:name]
因此它将打印出结果,我在将其更改为erb格式一段时间后找到了解决方案。