I have download the template Rails 3 + Mongoid + Devise and installed.
I have create a scaffold Car for relation with User model of Devise. I have in my User model this code:
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_se开发者_开发百科nsitive => false
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
embeds_many :cars
end
and My Cars Model I have the next code:
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
When I refresh the page I get the next error:
Mongoid::Errors::InvalidCollection in Cars#index
Access to the collection for Car is not allowed since it is an embedded document, please access a collection from the root document.
What its the problem in this code? Thankyou
There is nothing wrong with your model but the routes and controller actions that the scaffold generated are attempting to run a query on the Cars collection directly and because Cars are embedded in User you cannot do that with Mongoid as the error message indicates. As it stands Cars are only accessible through a User object.
There are a couple of possible ways around this. First, without changing the model, you would need to alter the routes and actions. With this model (Cars embedded in Users) it probably makes sense to use a nested route:
resources :users do
resources :cars
end
This will mean lead to the URL users/:user_id/cars mapping to the index action in the CarsController which might look something like this:
def index
user = User.find(params[:user_id])
@cars = user.cars
# code to render view...
end
The important point here is that you are accessing the cars for a given user. The same principle applies to the other actions.
The second option would be to change your model to use a referenced relation rather than an embedded one but if the model is right the way it is then its better to change the controller and routes.
精彩评论