在从表单输入另一部分的同时显示多维数组的一部分?

Display one piece of a multidimensional array while entering another from a form?

我需要能够输入一个字符串值,并让它在 table 上输入该行的 ID。

我正在尝试让 HTML 中的 select 标签在 Ruby 中工作。但是,当新行添加到我从中提取值的 table 时,我需要它以编程方式更改。

table 本身看起来像这样:

Locations
 id    location_cd
| 1  |         SLC|
| 2  |         LAS|

我使用位置 class 将这些值从这个 table 传递到数组中。这是位置 class。

class Location < ActiveRecord::Base

    def self.select_options
        self.all.sorted.collect{ |q| [q.id, q.location_cd]}
    end


end

当我调用 select_options 方法时,这样做会得到这个多维数组。

[[1, "SLC"], [2, "LAS"]]

这是我在控制器中的内容。

def edit
    @pallet = Pallet.find(params[:id])
    @locations = Location.all
  end

  def update
    @pallet = Pallet.find(params[:id])
    if @pallet.update_attributes(pallet_params)
      flash[:notice] = "Pallet Updated Successfully."
      redirect_to(:action => 'show', :id => @pallet.id)
    else
      @pallet_count = Pallet.count
      render('edit')
    end
  end

托盘是我从中提取的主要 class,我需要将 location.id 输入托盘 table。

这是我正在编辑的内容。

<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>

<div class="pallets edit">
    <h2>Update Pallet</h2>

    <%= form_for(:pallet, :url => {:action => 'update', :id => @pallet.id}) do |f| %>

        <%= render(:partial => "form", :locals => {:f => f}) %>

        <div class="form-buttons">
            <%= submit_tag("Update Pallet") %>
        </div>

    <% end %>
</div>

这会将其重定向到表单,这是我表单中的内容。这就是我 运行 遇到的问题所在。

<table summary="Pallets from fields">
    <tr>
        <th><%= f.label(:destination) %></th>
    </tr>
    <tr>
        <td><%= f.select(:destination, Location.select_options) %></td>
    </tr>
</table>

这样做会给我一个像这样的 id 的列表。

1
2

但是我想要一个这样的 location_cd 列表。

SLC
LAS

但我需要它达到可以输入 SLC 的程度,而在数据库中它会输入 1。

为了从 multidimensional array 的角度来看,我需要能够在用户端输入 [[1, "SLC"]] 的第二个值,以及第一个值 (1)应输入table。

我进行了大量挖掘工作,终于找到了有用的东西。

有一个 rails 附带的助手,叫做 options_for_select()。它的作用是需要这样的东西

<%= select_tag(:destination, '<option value="1">SLC</option>...') %>

它会使用 multidimensional array

自动生成选项

由于我已经通过使用 select_options 方法获得了 multidimensional array,因此我能够像这样将它们结合使用:

<td><%= select_tag(:destination, options_for_select(Location.select_options)) %></td>

这正是我所需要的,并在选择时将正确的值附加到数据库。

另一种方法没有 options_for_select 帮助程序,但它需要有一个参数可供选择行。

@pallet = Pallet.find(2)

<td><%= select(:pallet, :destination, Location.select_options) %></td>

这个的优点是它会自动默认为已经存在的内容。这使您在更新位置以外的内容时更容易。