【发布时间】: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