我最近将一张表分成了三个单独的表格,现在无法将它们组合成一个列表。
我有一个场地 - 有很多订单 - 有很多项目
试图列出场地的所有订单和附带信息:
app.rb
get "/:venue/orders" do
@venue = Venue.find_by_handle(params[:venue])
@orders = Order.joins(:venue).where(:venues => {:handle => @venue.handle})
@items = Item.joins(:order).where(:orders => {:id => @orders.id})
erb :"venue/index"
end
地点/ index.erb
<% @orders.each do |order| %>
<h3>Order <%= order.id %></h3>
<h4><%= @customer.email %></h4>
<% @items.each do |item| %>
<h5><%= item.quantity %> x <%= item.item %></h5>
<% end %>
<% end %>
models.rb
class Order < ActiveRecord::Base
belongs_to :venue
belongs_to :customer
has_many :items
validates :venue_id, presence: true
end
class Item < ActiveRecord::Base
belongs_to :order
validates :order_id, :presence => true
validates :quantity, :presence => true
validates :item, :presence => true
end
class Customer < ActiveRecord::Base
has_many :orders
validates :email, :presence => true
end
class Venue < ActiveRecord::Base
has_many :customers, :through => :orders
has_many :orders
validates :name, :presence => true
validates :handle, :presence => true, :uniqueness => true
end
我收到了#id; id&#39;的NoMethodError并理解,因为我没有看特定的订单。如何查询必要的项目?
答案 0 :(得分:1)
这就是诀窍:
@venue = Venue.includes({:orders => [:customer, :items]}).find_by_handle(params[:venue])
然后,在您看来:
<% @venue.orders.each do |order| %>
<h3>Order <%= order.id %></h3>
<h4><%= order.customer.email %></h4>
<% order.items.each do |item| %>
<h5><%= item.quantity %> x <%= item.item %></h5>
<% end %>
<% end %>