2011-12-01 185 views
3

我有一些與MongoDB,Mongoid映射器和設計的rails應用程序。授權用戶可以創建,編輯,刪除文章(腳手架)並評論這篇文章。我拿Ryan Bates screencast的評論模型例子,238集「Mongoid」。Mongoid與設計關係

comment.rb

class Comment 
    include Mongoid::Document 
    field :name 
    field :content 
    embedded_in :post, :inverse_of => :comments 
end 

post.rb

class Post 
     include Mongoid::Document 
     field :name 
     field :content 
     validates_presence_of :name 
     embeds_many :comments 
    end 

user.rb

class User 
    include Mongoid::Document 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 

    field :username 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me 

    has_many :comments 
    references_many :post 

end 

但是當我嘗試註冊新用戶,在登記表推「註冊「,我看到這個錯誤

Mongoid::Errors::MixedRelations in Devise::RegistrationsController#create 

Referencing a(n) Comment document from the User document via a relational association is not allowed since the Comment is embedded. 

我用Mysql db啓動了這個應用程序,然後決定進入mongo。 我的錯誤在哪裏?

+0

您的問題需要一個更好的標題 - 以問題的形式。因爲它是模糊的。 – jcollum

+1

爲什麼不推出自己的認證?在rails 3.1中非常簡單。觀看這個railscast:http://railscasts.com/episodes/270-authentication-in-rails-3-1如果你絕對需要設計,我可以看一下,但有可能你自己做這個會更好/更簡單。 –

+0

@Tyler:Devise相當全面。它已經過很好的測試,並且已經有一段時間了。考慮到所涉及的時間,你必須提出一個非常有力的論證來滾動你自己。 – jcollum

回答

2

由於Comment已嵌入Post中,因此您應該具有User引用Post。嘗試在用戶中刪除has_many :comments

+2

我嘗試。它的工作原理,但如果我需要獲得所有用戶評論? – Eugene

+0

你不應該在帖子中嵌入用戶。你應該引用它。 http://mongoid.org/en/mongoid/v3/relations.html#has_many – lcguida