[英]Accessing another model from an .each loop in Rails
I am trying to create a restaurant manager app that has users, orders, and meals. 我正在尝试创建一个具有用户,订单和餐点的饭店经理应用。 User has many orders, order has many meals.
用户有很多订单,订单有很多餐。 I want a table that lists all orders by a user together with meals' names and prices.
我想要一个表,列出用户的所有订单以及餐食的名称和价格。 I have three models:
User
, Order
, and Meal
. 我有三种模型:
User
, Order
和Meal
。 While it's not a problem to access order_id
from this loop: 虽然从此循环访问
order_id
没问题:
- @userOrders.each do |order|
%tr
%td= order.id
when I try to access meal's name by 当我尝试通过访问膳食名称时
- @userOrders.each do |order|
%tr
%td= order.id
%td= order.meals.name
here's what I get: 这是我得到的:
Table with what's supposes to be meals' names 带有食物名称的表格
In Ruby console, when I type user.orders[1].meals
, I get: 在Ruby控制台中,当我输入
user.orders[1].meals
,我得到:
This is my orders_controller.rb
这是我的
orders_controller.rb
def index
user_id = current_user.id
@userOrders = Order.where(:user_id => user_id)
end
Below is my order.rb
: 以下是我的
order.rb
:
class Order < ApplicationRecord
belongs_to :user
has_many :meals
end
user.rb
: user.rb
:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :orders
end
and meal.rb
: 和
meal.rb
:
class Meal < ApplicationRecord
belongs_to :order
end
Order has many meals. 点了很多餐。 Many meals can't have just one name for them all.
许多餐不能只用一种名称。 That's what you're trying to do with
order.meals.name
. 这就是您要使用
order.meals.name
。 Each meal has its own name. 每顿饭都有自己的名字。 Iterate meals too.
也要重复吃饭。 Something like this:
像这样:
- orders.each do |order|
- order.meals.each do |meal|
= meal.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.