【问题标题】:Mongoid + devise error Mongoid::Errors::InvalidCollectionMongoid + 设计错误 Mongoid::Errors::InvalidCollection
【发布时间】:2011-09-30 10:32:36
【问题描述】:

我已经下载并安装了模板 Rails 3 + Mongoid + Devise。

我已经创建了一个脚手架 Car 用于与 Devise 的 User 模型的关系。我的用户模型中有这段代码:

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 的集合,因为它是嵌入式文档,请从根文档访问集合。

这段代码有什么问题?谢谢你

【问题讨论】:

    标签: ruby-on-rails devise mongoid


    【解决方案1】:

    您的模型没有任何问题,但是脚手架生成的路由和控制器操作正在尝试直接对 Cars 集合运行查询,并且由于 Cars 嵌入在 User 中,因此您无法使用 Mongoid 执行此操作,如错误消息所示。就目前而言,汽车只能通过用户对象访问。

    有几种可能的方法来解决这个问题。首先,在不更改模型的情况下,您需要更改路线和操作。使用这种模型(嵌入用户中的汽车),使用嵌套路由可能是有意义的:

    resources :users do
      resources :cars
    end
    

    这意味着将 URL users/:user_id/cars 映射到 CarsController 中的 index 操作,这可能看起来像这样:

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

    这里的重点是您正在访问给定用户的汽车。同样的原则也适用于其他动作。

    第二种选择是更改您的模型以使用引用关系而不是嵌入式关系,但如果模型正确,那么最好更改控制器和路由。

    【讨论】:

    • 我已经使用了引用,现在很好:D。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多