【问题标题】:How to save embedded classes in mongoid?如何在 mongoid 中保存嵌入式类?
【发布时间】:2012-11-14 23:17:25
【问题描述】:

我正在使用带有 mongoid 2 的 Rails 3。我有一个 mongoid 类论坛,其中嵌入了多个主题。 主题 embeds_many forumposts

当我尝试在我的控制器中保存论坛帖子时...

@forum = Forum.find(params[:forum_id])
@forum.topics.find(params[:topic_id]).forumposts.build(:topic_id => params[:forumpost][:topic_id], :content => params[:forumpost][:content], :user_id => current_user.id,:posted_at => Time.now, :created_at => Time.now, :updated_at => Time.now)
if @forum.save

保存时我得到...

2012-11-14 23:15:39 UTC:Time 的未定义方法“每个”

为什么会出现这个错误?

我的论坛帖子类如下...

class Forumpost
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paranoia

  field :content, type: String
  field :topic_id, type: String
  field :user_id, type: String
  field :posted_at, type: DateTime

    attr_accessible :content, :topic_id, :user_id, :posted_at, :created_at, :updated_at

  validates :content, presence: true
  validates :topic_id, presence: true
  validates :user_id, presence: true

    belongs_to :topic
    belongs_to :user

end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid


    【解决方案1】:

    您的示例代码有很多错误/奇怪,所以让我们看看我们是否可以从头开始:

    您说论坛嵌入了许多主题,其中嵌入了许多帖子。但是您的模型正在使用 belongs_to 关联。 Belongs_to 用于与 嵌入文档 不同的引用。如果您的主题模型有这个:

    class Topic
      ...
      embeds_many :forumposts
      ...
    end
    

    那么你的 Forumpost 模型应该有这个:

    class Forumpost
      ...
      embedded_in :topic
      ...
    end
    

    在此处阅读参考与嵌入文档:http://mongoid.org/en/mongoid/docs/relations.html

    下一点,您不需要将 :topic_id 放入论坛帖子,因为您是根据主题构建的。

    下一点,不要保存论坛,保存论坛帖子。与其先构建然后保存,不如尝试一次性创建。

    下一点,尝试设置 user => current_user,而不是设置 user_id => current_user.id。这是 belongs_to 关联所提供的魔力……它更简洁,避免了与 ID 混淆。

    下一点,为什么需要 created_at(由 Mongoid::Timestamps 提供)和 posted_at ?

    最后一点,您不需要设置时间戳,它们应该在创建/更新时自动设置(除非出于某种原因您实际上需要posted_at)。

    试试这样的:

    @forum = Forum.find(params[:forum_id])
    @topic = @forum.topics.find(params[:topic_id])
    if @topic.forumposts.create(:content => params[:forumpost][:content], :user => current_user)
      #handle the success case
    else
      #handle the error case
    end   
    

    【讨论】:

    • 当我做你的帖子时,我收到了异常:NoMethodError (undefined method 'forumposts' 谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 2012-04-26
    相关资源
    最近更新 更多