简体   繁体   中英

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 . While it's not a problem to access order_id from this loop:

- @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:

Console output

This is my orders_controller.rb

  def index
    user_id = current_user.id
    @userOrders = Order.where(:user_id => user_id)    
  end

Below is my order.rb :

class Order < ApplicationRecord
  belongs_to :user
  has_many :meals
end

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 :

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 . Each meal has its own name. Iterate meals too. Something like this:

- orders.each do |order|
  - order.meals.each do |meal|
    = meal.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM