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

  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}"
  end
end
  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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值