سؤال

في النموذج الخاص بي ، لدي الحقول التالية:

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

ولدي أيضًا نموذج لتقديم الحقول التي قد يوفرها "المعلق":

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

الحقول "المؤلف" و "المحتوى" مطلوبة ، يتم ملء الآخرين تلقائيًا (ولكنهم يعملون). المشكلة هي أنه عندما لا يملأ المستخدم حقل "url" ، وهو أمر اختياري ، فإن النموذج لا يحفظ التعليق. بعد وحدة التحكم الخاصة بي:

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

فشل التعليق في الحفظ ، ولكن لم يتم تعيين "تنبيه" ، ولا "إشعار". يبدو أنه مجرد تعطل ويتخطى الطريقة بأكملها. لا يمكنني إلا حفظ التعليق إذا تم ملء كل حقل ، وإلا فإنه سيفشل بدون أي رسالة.

ماذا ينقصني؟

هل كانت مفيدة؟

المحلول

أول ما يتبادر إلى الذهن هو أنك تنقذ التعليق مرتين لسبب ما. أولا عليك حفظه عند استخدام @article.comments.create(comment_params) بدلا من ذلك @article.comments.new(comment_params). لذلك فشل الحفظ الأول بدون فلاش.

أود أن أوصي أيضًا بتطبيق بعض الاختبارات لمعرفة ما لا يعمل أو على الأقل باستخدام debugger gem إلى سنك داخل الكود في العمل.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top