rails 中使用association 生成select 下拉框的一些小技巧

来源:互联网 发布:好用的游戏优化软件 编辑:程序博客网 时间:2024/06/06 21:51
  1. 根据关联表来生成下拉框
    在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 %>

其中:match_subject 是和model中定义的 belongs_to的名称所对应

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}"  endend
  1. 下拉框不生成一个空白项目
    include_blank: false
    这个选项就是告诉association不用生成一个空白项
  2. 下拉框包含一个空白项目,并且指定显示的文字
    如果希望生成一个空白项,并且指定空白项显示的内容,就可以用下面的预计,空白项内容显示为:select if none
    :include_blank => “(select if none)”
  3. 下拉框列表只读
match_subject_select_div  =  $("#match_subject_select_div").select2 (    placeholder: "请选择一个主题",    width: "200px",    theme: "classic"  ) match_subject_select_div.select2("enable", false)
0 0