【问题标题】:Unable to update the fields from edit form using rails无法使用 rails 更新编辑表单中的字段
【发布时间】:2018-11-29 11:17:58
【问题描述】:

在我的索引视图中,对于编辑按钮,我有以下代码:

<td id="EditButton"><%= link_to "Edit", edit_comment_path(data.Metric+","+data.HouseId+","+data.ADate.to_s) %></td>

在我的评论控制器中,我有以下用于编辑和更新的代码:

def edit
            edit_array=params[:id].split(',')
            @one = edit_array[0]
            @two = edit_array[1]
            @three = edit_array[2]
            @comment = Comment.find_by(Metric: @one , HouseId: @two , ADate: @three)      
end
       def update
            @comment = Comment.find(params[:id])
            if @comment.update(comments_params)
              redirect_to metrics_path
            else
              render 'edit'
            end   
    end        

我的编辑表单中有这个表单标签:

<%= form_for :comments_controller, url: comments_path(@comment) do |f| %>

编辑表单中的字段:

<tr>
          <td><%= @comment.Metric %></td>
          <td><%= @comment.HouseId%></td>
          <td><%= @comment.ADate%></td>
          <td><%= f.select :IsAlarmCreated, options_for_select([["True", "1"], ["False", "0"]]), :class => 'chosen-select', :required => true, selected: @comment.IsAlarmCreated  %></td>
          <td><%= f.text_field :UserName, value: @remote_user %></td>
          <td><%= f.text_field :Comments, value: @comment.Comments, required: true  %></td>
          <td><%= f.submit "Save"%></td>

我正在执行以下操作: 索引页面被加载 单击编辑后,它导航到编辑页面 我将对字段进行一些更改,然后单击保存 现在,它被重定向到 cmets 并出现以下错误:

无法为 CommentsController 找到“创建”操作

更新 mysql 中的值后,期望重定向到 Metric 控制器的索引视图。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 form-for actioncontroller


    【解决方案1】:

    您为表单使用了错误的路径,使用comment_path(@comment)(单数)。 comments_path(@comment) 导致 /comments.123 而不是 /comments/123

    也有可能在#edit 方法中找到的@commentnil 并且表单提交到/comments 路径。

    https://guides.rubyonrails.org/routing.html#path-and-url-helpers

    【讨论】:

    • 使用单数形式 (comment_path(@comment)) 给我错误:没有路由匹配 {:action=>"show", :controller=>"cmets", :id=>nil}缺少必需的键:[:id]
    • 添加这两个用于验证:puts @comment puts @comment.class 导致#&lt;Comment:0x00007fbf7d1364d0&gt; Comment
    • 这意味着 @commentnil (正如我在答案的第二部分中所说),您需要修复获取它的方式。我建议使用普通的旧整数 id 而不是这种复杂的日期/度量结构
    • 你把它放在哪里了?还要检查@comment.id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多