【问题标题】:Rails 3: How do I create options in a <select> tag from rows in a database table?Rails 3:如何从数据库表中的行在 <select> 标记中创建选项?
【发布时间】:2011-08-11 03:33:55
【问题描述】:

给定以下形式:

<%= form_for(@ciudad) do |f| %>
  <% if @ciudad.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@ciudad.errors.count, "error") %> prohibited this ciudad from being saved:</h2>

      <ul>
        <% @ciudad.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :nombre %><br />
    <%= f.text_field :nombre %>
  </div>

  <div class="field">
    <%= f.label :departamento_id %><br />
    <%= f.select :departamento_id , :prompt => "Seleccione el municipio" %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

如何从数据库中填充 deparamento_id 选择标签的选项?

【问题讨论】:

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


    【解决方案1】:

    最简单的方法是使用f.collection_select 而不是f.select。假设您有一个名为 Departamento 的表/模型,其中有一个名为 nombre 的字段:

    <%= f.collection_select :departamento_id, Departamento.all, :id, :nombre, :prompt => "Seleccione el municipio" %>
    

    您可以在此处的官方 Rails 指南中阅读更多相关信息:http://guides.rubyonrails.org/form_helpers.html#option-tags-from-a-collection-of-arbitrary-objects

    在 API 文档中: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2011-04-24
      • 2011-05-24
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多