Question

Dans mon modèle, j'ai les champs suivants:

class Comment
  include Mongoid::Document

  field :author, type: String
  field :author_email, type: String
  field :author_url, type: String
  field :author_ip, type: String
  field :content, type: String

  validates :author, presence: true, length: { minimum: 4 }
  validates :content, presence: true, length: { minimum: 8 }
end

Et j'ai également un formulaire pour soumettre les champs que le "commentateur" peut fournir:

<%= form_for [@article, @article.comments.build] do |f| %>
  <div class='comment_content'>
    <%= f.text_area :content %>
  </div>

  <div class='comment_author_email'>
    <%= f.email_field :author_email %>
  </div>

  <div class='comment_author'>
    <%= f.text_field :author %>
  </div>

  <div class='comment_author_url'>
    <%= f.url_field :author_url %>
  </div>

  <div class='comment_submit'>
    <%= f.submit %>
  </div>
<% end %>

Les champs «auteur» et «contenu» sont requis, les autres sont automatiquement remplis (mais fonctionnent). Le problème est que lorsqu'un utilisateur ne remplit pas le champ "URL", ce qui est facultatif, le modèle n'enregistre pas le commentaire. Suivant mon contrôleur:

class CommentsController < ApplicationController
  def create
    @article = Article.find params[:article_id]
    @comment = @article.comments.create(comment_params)
    @comment.author_ip = request.remote_ip
    if @comment.save
      flash[:notice] = 'Comment published'
    else
      flash[:alert] = 'Comment not published'
    end
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:content, :author_email, :author, :author_url)
    end
end

Le commentaire ne parvient pas à enregistrer, mais aucune "alerte" n'est définie, ni "avis". Il semble que cela se bloque et saute toute la méthode. Je ne peux enregistrer le commentaire que si chaque champ est rempli, sinon il échouera sans aucun message.

Qu'est-ce que je rate?

Était-ce utile?

La solution

The first thing that comes to mind is that you are saving the comment twice for some reason. First you save it when using @article.comments.create(comment_params) instead on @article.comments.new(comment_params). So the first save fails with no flash.

I'd also recomend you applying some tests to see what's not working or at least using the debugger gem to sneek inside the code in action.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top