【问题标题】:I am trying to add comments withour refresh a page我正在尝试添加评论而不刷新页面
【发布时间】:2020-04-28 23:06:21
【问题描述】:

当我尝试添加评论时,它不会附加到表格上。当我刷新页面时,它会追加。我不知道有什么问题。我认为我做的一切都很好。页面上没有错误。无论我添加到表格中,它都会进入表格,但只有在刷新页面之后。

show.html.erb

...
<table id="comments">
  <tbody>
    <% @article.comments.each do |comment| %>
      <%= render 'comments/comment', comment: comment %>
    <% end %>
  </tbody>
...

_comment.html.erb

<tr>
  <td><p><%= comment.name %></p></td>
  <td><p><%= comment.body %></p></td>
  <td><p><%= time_ago_in_words(comment.created_at) %> Ago</p></td>
  <% if User.find_by(email: comment.name) == current_user %>
    <td><%= link_to 'Delete', [comment.article, comment], method: :delete, data: { confirm: 'Are you sure?' } %></td>
  <% else %>
    <td> </td>
  <% end %>
</tr>

create.js.erb

$('table#comments tbody').append("<%= j render @comment %>")

终端

ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/comments_controller.rb:7:in `create'

routes.rb

Rails.application.routes.draw do


  get 'search/index'

  devise_for :users
  get 'welcome/index'
  get '/search', to: 'search#search'



  resources :user
  resources :articles do
    resources :comments
    member do
      put "like" => "articles#like"
      put "unlike" => "articles#unlike"
    end
  end
  resources :search, only: [:index]

  root 'welcome#index'
end

cmets_controller.rb

def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(params[:comment].permit(:name, :body))
    @comment.name = current_user.email
    respond_to do |format|
        if @comment.save
            format.js 
            format.html { redirect_to @comment }
            format.json { render :show, status: :created, location: @comment }
        else

        end
    end
end

【问题讨论】:

  • 在您的控制器中需要呈现为js 格式,同样 - 评论应使用remote: true 提交
  • 我编辑问题并添加我的控制器。你能看一下并告诉我我需要它吗?

标签: javascript ruby-on-rails ruby forms


【解决方案1】:

你的控制器应该是这样的:

def create
 ............ 
 if @comment.save
    respond_to do |format|
      format.js
    end
  end 
end

处理错误:在create.js.erb 文件中,检查@comment.errors.any? - 然后做任何你想做的事情。

【讨论】:

    【解决方案2】:

    因为默认情况下,控制器返回的格式是html。所以你需要在控制器中添加另一个共振峰js 以使js.erb 工作。

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2022-11-20
      • 2014-07-11
      • 1970-01-01
      相关资源
      最近更新 更多