【问题标题】:Rails - How to implement :remote => true, to edit comments on the same pageRails - 如何实现:remote => true,在同一页面上编辑评论
【发布时间】:2017-10-15 14:18:52
【问题描述】:

我正在使用 Rails 5 构建一个活动站点。在 Event#show 页面上,我有一个 cmets 部分,我想在用户不离开页面的情况下为其提供编辑/更新功能。 我正在尝试在表单中使用:remote => true,但我遇到了错误,这是视图和控制器代码 -

cmets/_form.html.erb

<%= simple_form_for([@event, @event.comments.build, :remote => true ]) do |f| %>


    <%= f.label :comment %><br>
    <%= f.text_area :body %><br>
    <br>
    <%= f.button :submit, label: 'Add Comment', class: "btn btn-primary" %>
<% end %>

Comments_controller.rb

def update

    respond_to do |format|
      if @comment.update
        format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
        format.js   { }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

我得到的当前错误是 {:remote=>true}:Hash 的“未定义方法 `model_name”。这指向事件控制器中的 events#show 方法。我不确定我在正确的位置使用 :remote => true 因此出现错误。这是我第一次这样做,所以我在每一步都遇到错误。任何帮助/协助将不胜感激。

【问题讨论】:

  • 尝试将:remote =&gt; true移出数组:simple_form_for([@event, @event.comments.build], remote: true)
  • 谢谢,这已经消除了错误,但页面不允许我更新评论。我需要包含一个 js.erb 文件吗?
  • @event.comments.build 构建了一个新的comment 的结构,这个新的(尚未保存的)对象以f 的形式用于构建整个表单的html 结构。简短的回答,该表单必须指向create 而不是update,为什么?,正如我告诉你的@event.comments.build 构建了一个尚未保存的新comment
  • 那么,我将哈希更改为什么?还是我在控制器中调整create方法?
  • 当您单击Add Comment 时,rails 控制台会向您显示什么,请求是否转到create 操作?,它应该转到那里;因此,如果您没有 create 操作,请添加它,并且您必须调整您的代码,以便它使用给定的参数创建一个新的 comment

标签: ruby-on-rails ruby ajax model-view-controller


【解决方案1】:

您使用的simple_form_for 格式不正确。应该是

<%= simple_form_for([@event, @event.comments.build], remote: true ) do |f| %>

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多