К материалу
Подключаем Recaptcha в Rails application
. Как стало уже обычным, львиная доля кода из блога выносится на форум... не будем отступать от традиций. Итак.
Не сочетайте render и redirect_to. Если необходимо передать вместе с редиректом то или иное сообщение, можно использовать flash или error, например:
comments_controller.rb
Code:
class CommentsController < ApplicationController
http_basic_authenticate_with name: "admin", password: "12345", only: :destroy
def create
@article = Article.find(params[:article_id])
if verify_recaptcha
@comment = @article.comments.create(comment_params)
redirect_to article_path(@article)
flash.notice = 'You have added a comment!'
else
redirect_to article_path(@article)
end
end
def destroy
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
@comment.destroy
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
_form.html.erb
Code:
<%= form_for([@article, @article.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<div>
<%= recaptcha_tags %>
</div>
<% flash.each do |key, message| %>
<p class="<%= key %>"><%= message %></p>
<% end %>
<p>
<%= f.submit %>
</p>
<% end %>
Или:
comments_controller.rb
Code:
class CommentsController < ApplicationController
http_basic_authenticate_with name: "admin", password: "12345", only: :destroy
def create
@article = Article.find(params[:article_id])
if verify_recaptcha
@comment = @article.comments.create(comment_params)
redirect_to article_path(@article)
else
flash[:error] = 'Recaptcha error!'
redirect_to article_path(@article)
end
end
def destroy
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
@comment.destroy
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
_form.html.erb
Code:
<%= form_for([@article, @article.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<div>
<%= recaptcha_tags %>
</div>
<% if flash[:error] %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>
<p>
<%= f.submit %>
</p>
<% end %>