rails 에서 association 을 사용 하여 select 드 롭 다운 상 자 를 만 드 는 작은 기술

4
  • 관련 표 에 따라 드 롭 다운 상 자 를 생 성하 여 view 보기에 서 이러한 드 롭 다운 상 자 를 정의 합 니 다
  • <%= f.association :match_subject,collection: MatchSubject.all,  include_blank: false ,:input_html => { :class => 'span200 chzn-select' , :id => "match_subject_select_div"}, :label => MatchInfo.human_attribute_name(:subject_id), label_html: { class: 'input_label span200' }, :label_method =>  :display_code_and_name , :value_method => :id %>

    그 중:matchsubject 는 model 에서 정의 하 는 belongsto 의 이름 에 대응
    class MatchInfo < ActiveRecord::Base
      belongs_to :user , :foreign_key => :user_id ,:primary_key => :id 
      belongs_to :match_subject ,:foreign_key => :subject_id ,:primary_key => :id
    
      validates :subject_id,  presence: true 
    end
    

    :label_method => :display_code_and_name 은 메 인 테이블 에 정 의 된 디 스 플레이 방법 입 니 다.
    class MatchSubject < ActiveRecord::Base
      def display_code_and_name
        "#{code} - #{name}"
      end
    end
    
  • 드 롭 다운 상 자 는 공백 항목 include 를 생 성하 지 않 습 니 다.blank:false 이 옵션 은 association 에 공백 항목 을 만 들 지 않 아 도 된다 는 것 을 알려 주 는 것 입 니 다
  • 드 롭 다운 상 자 는 빈 항목 을 포함 하고 표 시 된 텍스트 를 지정 합 니 다.빈 항목 을 만 들 고 빈 항목 에 표 시 된 내용 을 지정 하려 면 아래 의 예상 을 사용 할 수 있 습 니 다.빈 항목 의 내용 은 select if none:include 로 표 시 됩 니 다.blank => “(select if none)”

  • 드 롭 다운 상자 목록 읽 기 전용
    match_subject_select_div  =  $("#match_subject_select_div").select2 (
        placeholder: "       ",
        width: "200px",
        theme: "classic"
      )
     match_subject_select_div.select2("enable", false)

    좋은 웹페이지 즐겨찾기