1

问题:

用户下拉菜单显示 ActiveRecord 关系

我希望下拉列表列出用户的姓氏。怎么能做到这一点?

app/controllers/courses_controller

  def edit
    @course = Course.find(params[:id])
    @teachers = User.where('teacher is true').order(:last_name).all
  end

看法

= simple_form_for @course do |f|
  - if @course.errors.any?
    #error_explanation
      %h2= "#{pluralize(@course.errors.count, "error")} prohibited this course from being saved:"
      %ul
        - @course.errors.full_messages.each do |msg|
          %li= msg

  .field
    = f.input :name
  .field
    = f.input :password
  .field
    = f.input :description
  - if @current_user
    - if @current_user.admin?
      = f.input :user, collection: @teachers
  .actions
    = f.submit 'Save', class: 'btn btn-primary'
4

1 回答 1

1

文档

除了集合之外,集合输入还接受另外两个选项:

• label_method => 应用于集合以检索标签的标签方法(使用此方法代替collection_select 中的text_method 选项)

• value_method => 应用于集合以检索值的值方法

= f.input :user, collection: @teachers, label_method: :last_name
于 2013-04-11T03:22:55.743 回答