2011-09-30 122 views
0

我已經下載了模板Rails 3 + Mongoid + Devise並安裝。Mongoid + devise error Mongoid :: Errors :: InvalidCollection

我已經創建了一個腳手架汽車關係用戶設計模型。我有我的用戶模型驗證碼:

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 :name 
    validates_presence_of :name 
    validates_uniqueness_of :name, :email, :case_sensitive => false 
    attr_accessible :name, :email, :password, :password_confirmation, :remember_me 

    embeds_many :cars 

    end 

和我的汽車模型我有下面的代碼:

class Car 
    include Mongoid::Document 
    field :title 
    field :description 
    field :image_url 
    field :price 
    field :published_on, :type => Date 
    validates_presence_of :title, :description, :image_url, :price 
validates :title, :length => { :maximum => 70 } 
validates :description, :length => { :maximum => 2000 } 
validates :price, numericality: {greater_than_or_equal_to: 0.01} 
validates :image_url, allow_blank: true, format: { 
    with: 
    %r{\.(gif|jpg|png)$}i, 
    message: 'must be a URL for GIF, JPG or PNG image.' 
    } 

    embedded_in :user, inverse_of: :cars 

end 

當我刷新頁面,我得到了一個錯誤:

Mongoid :: Errors :: InvalidCollection in Cars#index

不允許訪問Car的集合,因爲它是一個emb edded文檔,請從根文檔訪問集合。

這個代碼有什麼問題? Thankyou

回答

1

您的模型沒有問題,但腳手架生成的路線和控制器操作正試圖直接在Cars集合上運行查詢,並且由於Cars嵌入在用戶中,所以您無法使用Mongoid作爲錯誤消息表示。就目前而言,汽車只能通過用戶對象訪問。

有幾種可能的解決方法。首先,不改變模型,你需要改變路線和行動。在這種模式下(嵌入在用戶汽車),它可能是有意義的使用嵌套的路線:

resources :users do 
    resources :cars 
end 

這將意味着導致該URL的用戶/:USER_ID /汽車映射在CarsController索引操作可能看起來這樣的事情:

def index 
    user = User.find(params[:user_id]) 
    @cars = user.cars 
    # code to render view... 
end 

這裏的重要一點是,您正在訪問給定用戶的汽車。其他行爲也適用同樣的原則。

第二個選擇是將您的模型更改爲使用引用關係而不是嵌入關係,但是如果模型正確,那麼更改控制器和路由將會更好。

+0

我有使用引用,現在罰款:D。非常感謝你! – hyperrjas