【问题标题】:Formtastic custom field in join table连接表中的 Formtastic 自定义字段
【发布时间】:2016-10-26 07:48:12
【问题描述】:

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

我的模型:

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 => :quotes_options" 我也有字段 ":quantity" 所以我也想更新它。所以我的观点是这样的,我将能够在联合表中保存数量

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

【问题讨论】:

    标签: ruby-on-rails activeadmin formtastic


    【解决方案1】:

    如果有人感兴趣,我是这样理解的:

     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? }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 2016-11-13
      相关资源
      最近更新 更多