1

我试图通过一个名为 orders_products 的连接表将订单和产品链接在一起,一个订单虽然有很多:products:order_products,但一个产品有很多:orders 虽然:order_products,但是当我保存表单并查看视图时没有显示该订单的产品。


new.html.erb 用于订单

<%= simple_form_for @order do |f| %>
<%= f.input :order_number %>

<%= hidden_field_tag "order[product][]", nil %>
<% Product.all.each do |product| %>
  <%= check_box_tag "order[product_ids][]", product.id, @order.product_ids.include?(product.id), id: dom_id(product) %>
  <%= label_tag dom_id(product), product.name %><br>
<% end %>

<%= f.submit %>

订单.rb

class Order < ActiveRecord::Base
  belongs_to :customer
  has_many :order_products, class_name: "OrderProduct"
  has_many :products, through: :order_products
end

产品.rb

class Product < ActiveRecord::Base
  has_many :order_products, class_name: "OrderProduct"
  has_many :orders, through: :order_products
end

order_product.rb

class OrderProduct < ActiveRecord::Base
  belongs_to :product
  belongs_to :order
end

show.html.erb 用于订单

<div class="well">
  <%= "Order number " + @order.order_number %>
  <% @order.products.each do |product| %>
    <%= product.name %>
  <% end %> 
</div>
4

0 回答 0