我想遍历数据库,为轨道表单上的下拉列表创建一个集合



以前在 rails 中创建表单时,当我创建下拉框时,我已经对下拉值进行了硬编码。但是现在我想创建一个下拉列表,它将从数据库中获取值,遍历并找到它需要在下拉列表中显示的值(最好按字母顺序(。这是否可能,如果可能,如何?

我有点这样想:

  <div class="field">
    <%= form.label :market_id %>
    <% array = [1, 2, 3] %>
    <%= form.text_field :market_id, collection: ["#{array}"] %>
  </div>

我正在创建的是一个人员数据库,我希望下拉列表能够查看该数据库并显示人员地址,例如

collection: people.suburb

但是某种循环来打印它们

在以前的网站中,我以这两种方式完成,对值进行硬编码

options_to_select...

 <div class="field">
    <%= form.label :startcolour, "Start Colour" %>
    <%= select_tag(:startcolour, options_for_select(['white', 'black', 'clear', 'acrylic black', 'grey', 'mixed', 'other'])) %>
  </div>

并使用集合:.....

    <%= f.input :description %>
    <%= f.input :fuel_type, collection: ["Petrol", "Diesel", "Hybrid"] %>
    <%= f.input :transmission_type, collection: ["Automatic", "Manual"] %>
    <%= f.input :location %>
    <%= f.file_field :pictures, multiple: true %>

我希望下拉列表随着人们将自己添加到数据库中而增长。

真的不知道从哪里开始,因为我没有弄乱太多表格,而且我在谷歌上找不到太多的爱。

谢谢

使用

<%= f.select :startcolour, Model.all.collect {|p| [ p.name, p.id ] }, {}, { :multiple => false, :size => 0 ,:class=> "", :id=> "" } %>

<%= f.select :startcolour, @model.collect {|p| [ p.name, p.id ] }, {}, { :multiple => false, :size => 0 ,:class=> "", :id=> "" } %>

并在相应的控制器操作中添加@model = Model.all

您可以使用选择查询在控制器中创建实例变量。

在控制器方法中,您可以编写 @names = Model.all.select(:name).order(name: :desc)

并查看您可以使用 <%= f.select :name, options_from_collection_for_select(@names, :name, :name, nil) %>

最新更新