【问题标题】:Strange Ghost Object appearing奇怪的幽灵物体出现
【发布时间】:2012-09-13 23:20:54
【问题描述】:

我目前有 3 个模型,UserModel (Devise)、一个 ArticleModel 和一个 CommentModel。

我使用 mongoid。

class Comment
  include Mongoid::Document
  field :body, type: String
  field :created_at, type: Time, default: DateTime.now
  belongs_to :article
  belongs_to :user
end

class Article
  include Mongoid::Document
  field :title, type: String
  field :body, type: String
  field :created_at, type: DateTime, default: DateTime.now
  has_many :comments
  belongs_to :user
end

class User
  include Mongoid::Document
  has_many :articles
  has_many :comments
end

我的文章/show.html.haml

.comments-form
        .row
    .span12
        = form_for([@article, @article.comments.build]) do |f|
            = f.text_area :body, :class => "span12", :rows => "3", :placeholder => "Your comment here..."
            = f.submit nil, :class => "btn"
.comments
    - @article.comments.each do |comment|
        .comment{:id => "#{comment.id}"}
            .row
                .span2
                    = image_tag("260x180.gif", :class => "thumbnail")
                .span10
                    = comment.body

我的 cmets_controller

class CommentsController < ApplicationController
  def new
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(params[:comment])
    @comment.user = current_user
    @comment.save
    redirect_to article_path(@article, notice: "Comment posted.")
  end
end

现在在我的文章/节目中出现了一个带有 id 但完全为空的评论,我只是无法弄清楚这个对象来自哪里......

【问题讨论】:

  • 你的new 操作应该是create,它应该使用@comment = @article.comments.build(params[:comment]) 而不是.create,它会尝试持久化对象。

标签: ruby-on-rails ruby-on-rails-3 mongoid3


【解决方案1】:

你的问题在于这一行:

= form_for([@article, @article.comments.build]) do |f|

当您调用@article.comments.build 时,您正在构建一条新评论并将其添加到@article.comments。当您迭代您的 cmets 时再往下看,您会看到刚刚创建的空的。

使用[@article, Comment.new],而不是[@article, @article.comments.build]

【讨论】:

  • 请不要添加“谢谢”cmets。如果您喜欢答案,请点赞。如果它回答了您的问题,accept it
猜你喜欢
  • 1970-01-01
  • 2013-12-16
  • 2018-06-23
  • 1970-01-01
  • 2019-06-13
  • 2018-09-20
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多