2016-10-26 3 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? }