连接表中的Formtastic自定义字段

时间:2016-10-26 07:48:13

标签: ruby-on-rails activeadmin formtastic

我需要在多对多连接表中设置自定义字段。现在我只能设置与复选框的关系,但我还需要设置数量字段。

我的模特:

class Quote < ApplicationRecord
  has_and_belongs_to_many :options,  :join_table => :quotes_options
  accepts_nested_attributes_for :options, :allow_destroy => true
end

class Option < ApplicationRecord
  has_and_belongs_to_many :quotes
end

并形成:

  form do |form|   
    form.inputs do
      form.input :options, :as => :check_boxes,:collection => Option.all
    end
 end

所以现在它被呈现为像

这样的复选框列表
New Quote
[X]  First option
[ ]  Second option

问题是在表格中:“join_table =&gt;:quotes_options”我还有字段“:数量”所以我也想更新它。所以我的观点就像,我将能够在联合表中保存数量

New Quote
[X]  First option    [       ] quantity
[ ]  Second option      [       ] quantity

1 个答案:

答案 0 :(得分:0)

如果有兴趣的话我会意识到这一点:

 form.inputs do
      Option.all.each do |option|
        form.semantic_fields_for :quote_options, form.object.quote_options.detect_or_build_by_quote(option) do |quote_option|
          quote_option.input :option_name_selected , :as => :boolean, :label => option.name
          quote_option.input :quantity , :as => :number
          quote_option.input :option_id , :as => :hidden
        end
      end

引用模型

  has_many :quote_options do
    def detect_or_build_by_quote(option)
      record = self.detect{ |quote_option| quote_option.option_id == option.id }
      if record.nil?
        record = self.new(:option_id => option.id)
      end
      record
    end
  end

  has_many :options,  :join_table => :quote_options
  accepts_nested_attributes_for :options, :allow_destroy => true        
  accepts_nested_attributes_for :quote_options , reject_if: proc { |attributes| attributes['quantity'].blank? or attributes['quantity'].to_f.zero? }