collection_check_boxes - 什么是正确的设置

时间:2016-08-10 11:03:15

标签: ruby-on-rails checkbox collection-select

模型

class Rfq < ActiveRecord::Base   
  belongs_to :purchase
  belongs_to :supplier
  belongs_to :customtemplate
end

class Purchase < ActiveRecord::Base 
  belongs_to :order

  #Products
  has_many :purchase_products, dependent: :destroy 
  has_many :products, through: :purchase_products
  accepts_nested_attributes_for :purchase_products, allow_destroy: true 

  validates :code, uniqueness: true
  validates :code, presence: true

  validates :order_id, presence: true  
end

class Supplier < ActiveRecord::Base
  has_many :products, dependent: :destroy
  accepts_nested_attributes_for :products, allow_destroy: true

  validates :code, uniqueness: true
  validates :code, presence: true
end


class Customtemplate < ActiveRecord::Base
    has_many :supplier_templates, dependent: :destroy, :foreign_key => 'customtemplate_id'
   has_many :suppliers, through: :supplier_templates 

   validates :code, uniqueness: true
  validates :code, :body, presence: true
end

rfqs_controller

class RfqsController < ApplicationController
(..)
def new
    @rfq = Rfq.new
    #@purchase_products = PurchaseProduct.where(purchase_id: params[:purchase_id])

    #RFQ for one purchase
    if params[:purchase_id].present?
      @a_products_suppliers = []

      products = Purchase.find(params[:purchase_id]).products
      @suppliers = products.select(:supplier_id).uniq

      products.each do |p|
        @a_products_suppliers.push(p.supplier_id => p.id)
        #binding.pry
      end
    end
    binding.pry

  end
(..)

其中一个模型字段是“产品”,定义为数组类型。

在控制器的@a_products_suppliers中,我收到了[{supplier_id =&gt; product_id}]

形式的哈希数组
(#<RfqsController>)> @a_products_suppliers
=> [{9=>5}, {9=>4}]

表格

<% @suppliers.each do |s| %>

  <%= simple_form_for @rfq do |f| %>
      <%= f.error_notification %>

      <h3>Products</h3>

      <% @a_products_suppliers.each do |a| %>
        <%= f.collection_check_boxes a[s.supplier_id] ???
      <% end %>

      <%= f.button :submit %>

  <% end %>
<% end %>

我无法弄清楚如何列出每个产品,允许用户使用复选框来定义哪些产品应存储在表rfqs的“产品”列中。

标签可以通过以下方式获得:Product.find(a[s.supplier_id]).code

可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

请尝试以下内容:

<%= collection_check_boxes(:student, :subject_ids, Student.order('name'), :id, :name) do |b| %>
   <%= b.check_box %>
   <%= b.label %>
<% end %>

我所在的学生 - 主题是多对多的关系。 collection_check_box本身就会迭代。

如果您遇到任何问题,请告诉我......