Question

In my model I have the following fields:

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

And I also have a form for submitting the fields the "commenter" may provide:

<%= 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 %>

The fields "author" and "content" are required, the others are automatically filled (but are working). The problem is, when a user does not fill the "URL" field, which is optional, the model does not save the comment. Following my controller:

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

The comment fails to save, but no "alert" is set, neither "notice". It seems like it just crashes and skips the whole method. I can only save the comment if every field is filled, otherwise it will fail without any message.

What am I missing?

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top