Rails form_for选择默认选项

时间:2014-04-16 17:19:11

标签: ruby-on-rails form-for

我有一个form_for选择从模型中定义选项的位置。我试图让它显示一个占位符选项,但无法弄清楚如何。

型号:

class Factoid < ActiveRecord::Base
  attr_accessible :description, :name, :title

  validates_presence_of :description, :name, :title
  validates_uniqueness_of :title


  NAMES = "Angela", "Geordie", "Jared", "Jennifer", "Kevin", "Matthew", "Oscar", "Owen", "Regina", "Todd", "Vaibhavi", "Zack"


  UNRANSACKABLE_ATTRIBUTES = ["id", "updated_at"]

  def self.ransackable_attributes auth_object = nil
    (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
  end

end

表格:

<%= form_for @factoid, :html => { :class => 'form-horizontal' } do |f| %>
  <div class="control-group">
    <%= f.label :title, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_field :title, :class => 'text_field' %>
    </div>
  </div>
  <div class="control-group">
    <%= f.label :description, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_area :description, :class => 'text_area' %>
    </div>
  </div>
  <div class="control-group">
    <%= f.label :name, :class => 'control-label' %>
    <div class="controls">
      <%= f.select :name, :collection => Factoid::NAMES %>
    </div>
  </div>

  <div class="form-actions">
    <%= f.submit nil, :class => 'btn btn-primary' %>
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                factoids_path, :class => 'btn' %>
  </div>
<% end %>

第二个问题是下拉菜单在其顶部显示“集合”一词(见下面的截图)。我怎么读这个。理想情况下,我想要一个带有“名称”占位符的下拉菜单,当打开下拉菜单时,该菜单也会显示在顶部。 Screenshot of the issue

1 个答案:

答案 0 :(得分:1)

对于您的文字字段,请尝试以下内容:

<%= f.text_field :title, :class => 'text_field', value: 'my_default_value' %>

选择尝试:

<%= f.select :name, Factoid::NAMES %>

有关典型用法的信息,请参阅the docs for selectthe rails guide(我认为我提供的方法在提交表单时无效,请参阅相关指南,但我不确定)