我已下载模板Rails 3 + Mongoid + Devise并已安装。
我已经为与用户 Devise模型的关系创建了一个支架 Car 。我在我的用户模型中有这段代码:
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 :: Car #index中的InvalidCollection
不允许访问Car的集合,因为它是嵌入式文档,请从根文档访问集合。
这段代码有什么问题?三江源
答案 0 :(得分:1)
您的模型没有任何问题,但脚手架生成的路径和控制器操作正在尝试直接在Cars集合上运行查询,并且因为汽车嵌入在用户中,您无法使用Mongoid执行此操作,因为错误消息指示。目前看来,汽车只能通过用户对象访问。
有几种可能的方法。首先,在不更改模型的情况下,您需要更改路线和操作。使用此模型(嵌入在用户中的汽车),使用嵌套路线可能是有意义的:
resources :users do
resources :cars
end
这将意味着导致URL users /:user_id / cars映射到CarsController中的索引操作,该操作可能如下所示:
def index
user = User.find(params[:user_id])
@cars = user.cars
# code to render view...
end
重要的一点是,您正在访问给定用户的汽车。同样的原则适用于其他行动。
第二种选择是将模型更改为使用引用的关系而不是嵌入的关系,但如果模型是正确的,则更好地更改控制器和路径。