ruby on rails - Mongoid::Errors::MixedRelations in AnswersController#create -
getting following error msg while saving answer:
problem: referencing a(n) answer document user document via relational association not allowed since answer embedded. summary: in order access a(n) answer user reference need go through root document of answer. in simple case require mongoid store foreign key root, in more complex cases answer multiple levels deep key need stored each parent hierarchy. resolution: consider not embedding answer, or key storage , access in custom manner in application code.
above error due code @answer.user = current_user in answerscontroller.
i want save login username answer embaded in question.
deivse user model:
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
using rails 4, ruby 2.2.2, mongoid.
that's error message says.
your answer model embedded in question model. say, can perform "normal" queries on question documents, , not on models embedded in 1 (actually can, it's more difficult , somehow kills point of using embedded documents).
so can user given answer, not inverse, have declared in user model.
the simplest solution remove has_many :answers
user model, if want retrieve list of answers given user, embedding models not best solution: should have relational models.
to make things clear, should write belongs_to :user, inverse_of: nil
Comments
Post a Comment