【问题标题】:Get id of an object to pass into form_for获取要传递给 form_for 的对象的 id
【发布时间】:2014-03-03 19:05:43
【问题描述】:

我正在尝试查找要传递给 form_for 的考勤表 ID

这是我的控制器

def show

    @time_id = current_user.time_sheets.find(params[:id])
    if current_user

      @current = current_user.time_sheets
    else
      redirect_to new_user_session_path, notice: 'You are not logged in.'
    end

  end

在我看来,这是我的 form_for:

<%= form_for(:entry, :url => {:controller => Entry, :action => 'create'}) do |f| %>

    <table summary="Subject form fields">
      <tr>
        <th>Customer</th>
        <td><%= f.text_field(:customer_name) %></td>
      </tr>
      <tr>
        <th>Order Number</th>
        <td><%= f.text_field(:order_number) %></td>
      </tr>
      <tr>
        <th>Time In</th>
        <td><%= f.text_field(:time_in) %></td>
      </tr>
      <tr>
        <th>Time Out</th>
        <td><%= f.text_field(:time_out) %></td>
      </tr>
      <tr>
        <th>Time Sheet ID</th>
        <td><%= f.hidden_field :time_sheet_id, value: @time_id.id %></td>
      </tr>

    </table>

    <div class="form-buttons">
      <%= submit_tag("Add Entry") %>
    </div>

  <% end %>

需要将时间表 ID 传递到 form_for 中,以便条目可以具有时间表 ID。

我有用户、时间表和条目。 user has_many time sheet,timesheets属于用户,用户有很多time sheet。条目属于时间表。

我收到此错误“找不到没有 ID 的 TimeSheet”

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 devise


    【解决方案1】:

    您应该使用“嵌套资源”,例如。见这里:Rails 3: How to create a new nested resource? 您可以使用 form_for([@timesheet, @entry]) 来传递时间表的 ID,而无需使用隐藏字段。如果你这样做, :url 参数也会过时。

    【讨论】:

      【解决方案2】:

      尝试添加:

      <%= @time_id.id %>
      

      输出您的变量并确保它与您的想法完全一致。如果@time_id 是一个时间表,您可能应该将该变量重命名为@time_sheet。

      【讨论】:

        猜你喜欢
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-11
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 2013-06-07
        相关资源
        最近更新 更多