獲得以下錯誤味精同時節省了一個答案:Mongoid ::錯誤:: MixedRelations在AnswersController#創建
問題:通過關係協會引用從用戶文檔(n)的回答文檔就再也沒有應答允許被嵌入。簡介:爲了正確訪問來自用戶的(n)答案,參考資料需要經過答案的根文件。在一個簡單的情況下,這需要Mongoid爲根存儲一個額外的外鍵,在更復雜的情況下,Answer是多層次的,需要爲每個父級在層次結構上存儲一個鍵。解決方案:考慮不嵌入Answer,或者在應用程序代碼中以自定義的方式執行密鑰存儲和訪問。
以上錯誤是由於在AnswersController中的代碼@ answer.user = current_user。
我想保存登錄用戶名到被問題的答案。
deivse用戶模型:
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
使用Rails 4,紅寶石2.2.2,Mongoid。
你提到':在你的控制器answerer',但我沒有看到這個在您的模型。此外,我不明白爲什麼你的答案模型中有'user_id'? –