Rails + MongoID - attribute request

I have a model like this:

class Lesson
  include Mongoid::Document

  field :title, :type => String
  field :category, :type => String
  field :price, :type => Float
  field :description, :type => String
  field :user_id, :type => String


  validates_presence_of :title
  validates_presence_of :category
  validates_presence_of :price
  validates_presence_of :user_id

  attr_accessible :title, :category, :description, :price

end

And I'm trying to query like this:

@lessons_by_user = Lesson.find_by_user_id current_user.id

And I get:

undefined method `find_by_user_id 'for the lesson: class

How can I execute a query on a specific attribute in MongoID?

I know how to do this:

@lessons = Lesson.all(:conditions=>{:user_id=>current_user.id.to_s}) 

but I wonder if there is a shortcut ...

+5
source share
2 answers

Mongoid does not have ActiveRecord-style automatic search methods; it only supports a limited set of predefined search methods :

  • Model.all
  • Model.count
  • Model.exists?
  • Model.find
  • Model.find_or_create_by
  • Model.find_or_initialize_by
  • Model.first
  • Model.last

However, it has a general method where, so you say this:

@lessons = Lesson.where(:user_id => current_user.id)

where ( where ActiveRecord), , .

+9

3.0.0 Mongoid, :

@lessons = Lesson.find_by(user_id: current_user.id)

where, Mongoid::Errors::DocumentNotFound, . , raise_not_found_error false, nil .

: http://mongoid.org/en/mongoid/docs/querying.html

+3

All Articles