当我尝试添加评论时,它不会附加在表格上。当我刷新页面时,它会追加。我不知道这是什么问题。我想我做得很好。页面上没有错误。不管我添加到表中什么,它都放在表中,但仅在刷新页面之后。
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
comments_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
答案 0 :(得分:1)
由于默认情况下,从控制器返回的格式为html
。因此,您需要在控制器中添加另一个共振峰js
才能使js.erb
正常工作。
答案 1 :(得分:0)
您的控制器应该是这样的:
def create
............
if @comment.save
respond_to do |format|
format.js
end
end
end
要处理的错误:在create.js.erb
文件中,检查@comment.errors.any?
-然后执行您想做的所有事情。