【问题标题】:Pass local variable to create.js.erb for an iteration in an iteration将局部变量传递给 create.js.erb 以进行迭代中的迭代
【发布时间】:2021-06-28 15:00:13
【问题描述】:

我有一个Post 和一个Comment 模型,而一个帖子可以有多个 cmets,一个评论属于一个帖子(和一个用户)。

我通过@posts.each do |d| 遍历所有帖子,这没什么大不了的。此外,我正在遍历 d.comments.each do |comment| 的所有帖子的 cmets。也没什么大不了的。

我设置了create.js.erb,让我的应用更加动态,并立即显示您在帖子下创建的评论。虽然我的表单工作正常,但我在设置 create.js.erb 时遇到了麻烦,这在提交表单内容时给了我一个 NameError - undefined local variable or method 'comment' for #<Class:> Did you mean? @comment:。重新加载页面后,评论被添加,但我希望像单页应用程序一样进行即时更新。我以前从未使用过 ajax。

如果我只是在单独的posts#show 视图上显示 cmets,我将能够解决整个情况,但是因为我正在遍历索引页面上的每个帖子,并且想要显示每个帖子的每条评论并更新cmets async 我只是不知道该怎么做。

如何创建所需的行为?

对不起,如果我的问题被问到有点不靠谱。

comments_controller.rb

  def create
    @user = current_user
    @comment = Comment.new(comment_params)
    @comment.user_id = @user.id

    respond_to do |format|
      if @comment.save
        format.js {}
        format.html { redirect_to root_path, notice: 'Comment added' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { redirect_to root_path }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

posts/index.html.erb

<% @posts.each do |d| %>
  <%= d.content %>

  <div class="comment-list">
    <%= render partial: "comments/comment", collection: d.comments %>
  </div>
<% end %>

comments/_comment.html.erb

<%# d.comments.reverse.each do |comment| %>
  <%= comment.content %>
<%# end %>

create.js.erb

$(".comment-list").append("<%= j render partial: "comments/comment" %>");

【问题讨论】:

  • 发布您的新评论视图

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-5


【解决方案1】:
$(".comment-list").append("<%= j render partial: "comments/comment" %>");

将上面的代码替换为

$(".comment-list").append("<%= j render partial: "comments/comment", locals: {comment: @comment} %>");

【讨论】:

  • 我不敢相信。我做了同样的事情,我发誓!但现在它的工作:D 非常感谢!
  • 欢迎您,您可以随时联系我@GabrielTheCoder
  • 你真好!也许你可以帮忙做另一件事。我的 _comment.html.erb 部分正在以“正确”的方式呈现 cmets。有没有办法像 .reverse 那样扭转订单? @MayurKambariya
  • $(".comment-list").prepend("");试试这个逆序
  • 将 append 替换为 prepend @GabrielTheCoder
猜你喜欢
  • 2021-05-16
  • 2012-12-24
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
相关资源
最近更新 更多