将属性列表添加到表单中的集合

时间:2013-02-18 09:06:25

标签: ruby-on-rails ruby-on-rails-3

我的目标是在表单中添加一个下拉框,为用户提供已有的所有“专业”列表。

我有一个指南模型,这个模型有一个属性:专业,但我不知道如何在views / guidelines / _form.html.erb中添加我的表单(我使用的是simple_form)

guidelines_controller.rb

def listspecialty

@speclist = Guideline.order(:specialty).uniq.pluck(:specialty)

def topicspecialty

 @guidelines = Guideline.find_all_by_specialty(params[:specialty])

视图/准则

new.html.erb

<%= render 'form', speclist: @speclist %>

* _ * form.html.erb

<%= f.input :specialty, as: :select, collection: speclist %>

listspecialty.html.erb

    <% @speclist.each do |specialty| %>
<%= link_to specialty, :action => :topicspecialty, :specialty => specialty %>

路线

get "guidelines/listspecialty"
  get "guidelines/topicspecialty"
  match "specialty", to: "guidelines#listspecialty", as: :specialty
  get '/:id', to: 'guidelines#topic'
  get '/:id', to: 'guidelines#topicspecialty'

1 个答案:

答案 0 :(得分:1)

simple_form试试这个:

<%= f.input :specialty, as: :select, collection: @list %>

您还可以将阵列代码简化为:

@list = @guidelines.map(&:specialty).uniq

或者,如果您仅针对@list获取指南,请执行:

@list = Guideline.order(:specialty).uniq.pluck(:specialty)

要将@list传递给您的表单,您可能需要将其传递给部分:

# guidelines controller
def list_specialty
  #some code
  @list = Guideline.order(:specialty).uniq.pluck(:specialty)
end

# routes, something like:
match "specialty", to: "guidelines#list_specialty", as: :specialty

# where you add your partial
<%= render 'form', list: @list %>

# then in your form
<%= f.input :specialty, as: :select, collection: list %>

更新

new.html.erbguidelines#new操作相关联,因此您要在视图中使用的任何代码也应该在操作中,例如:

# guidelines controller
def new
  @specialties = Guideline.order(:specialty).uniq.pluck(:specialty)
  @guideline = Guideline.new
end

# in guidelines/new.html.erb
<%= simple_form_for @guideline do |f| %>
  <%= f.input :some_attr %>
  <%= f.input :specialty, as: :select, collection: @specialties %>
  ....
<% end %>