所选值的字段

时间:2018-09-26 16:33:40

标签: ruby-on-rails ruby

我有一个表单,其中包含用于帮助的字段,我需要在Rails应用程序中获取每个字段的值。

<%= form.fields_for :expenses do |expense| %>
      <%= render 'expense_fields', f: expense %>
<% end %>
<%= link_to_add_fields "Add field", form, :expenses %>

expense_fields.html.erb

<div class="row">
  <div class="col-md-5">
    <div class="form-group">
        <%= f.label :expense_name %>
        <%= f.select(:expense_name, options_for_select([['Hotel', 'hotel'], 
        ['Registration', 'registration'], 
        ['Meals', 'meals'], 
        ['Flight', 'flight'], 
        ['Mileage', 'mileage'],
        ['Car Rental', 'car rental'],
        ['Parking', 'parking'],
        ['Traning', 'training']],), { include_blank: true }, id: 'principal_selection', class: 'form-control') %> 
    </div>
  </div>
    <% if current_user.admin? || current_user.principal? || current_user.super? %>
      <div class="col-md-3">
    <% else %>
      <div class="col-md-7">
    <% end %>
      <div class="form-group">
        <%= f.label :expense_cost %>
        <%= f.number_field :cost, class: 'form-control', placeholder: 'Cost', step: :any %>
      </div>
    </div>
  <% if current_user.principal? || current_user.admin? || current_user.super? %>
  <div class="col-md-4">
    <div class="form-group">
      <%= f.label :payment_type %>
      <%= f.select(:payment_type, options_for_select([['Out of pocket', 'Out of Pocket'], ['Corporate Card', 'Corporate Card'], ['PO', 'PO']], selected: "Half Day"), { include_blank: false }, class: 'form-control') %>
    </div>
  </div>
  <% end %>
</div>

我检查了各个导轨指南,但无法找到一种方法来直接提取选择助手中每个字段的值。有人有什么想法吗?

我尝试做selected: "#{@expense.expense_name}",但由于未定义@expense,因此显示nil错误。因此,我进入了pdforms控制器中的edit方法,并尝试了以下方法:

def edit
@expenses = @pdform.expenses
end

没有结果,所以我尝试了这个:

def edit
@expenses = @pdform.expenses
@expenses.each do |ex| 
  @expense = ex
end

但是在编辑表单时,它只是在表单中返回了一个值。还有其他想法吗?

1 个答案:

答案 0 :(得分:0)

使用fields_for时,随后引用的每个项目在每个.object实例上都可以作为field使用。因此,在这种情况下,请使用:

f.select(selected: f.object.expense_name  ...