2016-10-26 8 views
0

多対多結合テーブルでカスタムフィールドを設定する必要があります。今はチェックボックスとの関係しか設定できませんが、数量フィールドも設定する必要があります。結合テーブルの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 =>:quotes_options "私もフィールド"を持っています:数量 " eも更新します。だから、私の見解は次のようになり、私は関節の表に数量を保存することができます

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

答えて

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