Mongoid::Errors::MixedRelations 在 AnswersController#create

Mongoid::Errors::MixedRelations in AnswersController#create

保存答案时收到以下错误消息:

问题:由于嵌入了答案,因此不允许通过关系关联从用户文档引用 a(n) 答案文档。摘要:为了正确访问来自用户的 a(n) Answer,引用需要遍历 Answer 的根文档。在一个简单的情况下,这将需要 Mongoid 为根存储一个额外的外键,在更复杂的情况下,答案是多级深度的,需要为层次结构中的每个父级存储一个键。解决方案:考虑不嵌入 Answer,或者在应用程序代码中以自定义方式进行密钥存储和访问。

以上错误是由于代码 @answer.user = current_user in AnswersController.

我想将登录用户名保存到问题中嵌入的答案中。

设计用户模型:

class User
  include Mongoid::Document
  has_many :questions
  has_many :answers

class Question

  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Slug

  field :title, type: String
  slug :title

  field :description, type: String
  field :starred, type: Boolean

  validates :title, :presence => true, :length => { :minimum => 20, :allow_blank => false }

  embeds_many :comments
  embeds_many :answers

  #validates_presence_of :comments

  belongs_to :user

end

class Answer

  include Mongoid::Document
  include Mongoid::Timestamps

  field :content, type: String

  validates :content, :presence => true,  :allow_blank => false

  embedded_in :question, :inverse_of => :answers

  #validates_presence_of :comments

  belongs_to :user

end

class AnswersController < ApplicationController

  def create
    @question = Question.find(params[:question_id])
    @answer = @question.answers.create(params[:answer].permit(:answerer, :content))
    @answer.user = current_user
    redirect_to @question, :notice => "Answer added!"
  end
end

使用Rails4,Ruby2.2.2,Mongoid。

这正是错误消息所说的。

您的答案模型已嵌入到问题模型中。也就是说,您只能对问题文档执行 "normal" 查询,而不能对嵌入在该文档中的模型执行查询(实际上您可以,但它更难,并且不知何故扼杀了使用嵌入式文档的意义)。

因此您可以获得给定答案的用户,而不是您在用户模型中声明的相反答案。

最简单的解决方案是从用户模型中删除 has_many :answers,但如果您想检索给定用户的答案列表,那么嵌入模型可能不是最佳解决方案:您应该使用关系模型型号。

为了清楚起见,你应该写成belongs_to :user, inverse_of: nil