2011-02-27 33 views
0

我一直在尝试使用mongoid和referenced_in和references_many关联。我有两个模型,用户和问题。一个问题可以有一个作者,但是一个用户可以是一个作者多个问题。下面的代码片段显示了模型的结构。mongoid中referenced_in和references_many的控制器逻辑

class User 
    include Mongoid::Document 
    references_many :questions, :inverse_of => :poster, :dependent => :delete 
end 

class Question 
    include Mongoid::Document 
    referenced_in :poster, :class_name => "User" 
end 

现在,我的QuestionController#新情况如下

def create 
    @question = Question.new(params[:question]) 
    @question.poster = current_user 

    if @question.save 
    current_user.questions <<= @question 
    current_user.update_attributes(:questions => current_user.questions) 
    end 
end 

的question.poster字段被正确填充,但不填充user.questions阵列。什么才是正确的控制器逻辑呢?

回答

0

您的模特看起来不错。尽管如此,您不需要在控制器中完成所有这些工作。它应该看起来像这样:

def create 
    @question = current_user.questions.build(params[:question]) 

    if @question.save 
    #redirect logic goes here 
    end 
end 

您不需要明确地将问题添加到用户的问题数组中。

+0

嗨保罗,感谢您的答复。我尝试过,但是'User.first.questions'仍然返回'nil'。尽管'poster_id'字段反映了问题的值,用户中没有相应的字段。我如何访问用户的问题数组? – reddragon 2011-02-27 13:09:24

+0

当你打电话时它应该返回一个标准对象。你使用的是什么版本的mongoid? – 2011-03-01 13:28:27

+0

我正在使用2.0.0.rc.6。当我做'User.last.questions'时(我尝试通过应用程序为最后一个用户创建一个新问题),我得到'[]'。 – reddragon 2011-03-03 07:54:59

0

您是否通过以下方式

def create 
    @question = Question.new(params[:question]) 

    if @question.valid? 
    current_user.questions << @question 

    end 
end 

<<由mongoid覆盖尝试并节省current_user@question一次。

+0

谢谢,我试过了,但没有奏效。即使这样做后,问题数组仍然是空的。 'irb(main):009:0> User.last.questions' '=> []' – reddragon 2011-03-01 05:11:22

相关问题