ruby - Accessing another model from an .each loop in Rails -
i trying create restaurant manager app has users, orders, , meals. user has many orders, order has many meals. want table lists orders user meals' names , prices. have 3 models: user
, order
, , meal
. while it's not problem access order_id
loop:
- @userorders.each |order| %tr %td= order.id
when try access meal's name
- @userorders.each |order| %tr %td= order.id %td= order.meals.name
here's get:
table what's supposes meals' names
in ruby console, when type user.orders[1].meals
, get:
this orders_controller.rb
def index user_id = current_user.id @userorders = order.where(:user_id => user_id) end
below 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 , :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 1 name them all. that's you're trying order.meals.name
. each meal has own name. iterate meals too. this:
- orders.each |order| - order.meals.each |meal| = meal.name
Comments
Post a Comment