6

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 am trying to query like this:

@lessons_by_user = Lesson.find_by_user_id current_user.id

And I am getting:

undefined method `find_by_user_id' for Lesson:Class

How can I query by a specific attribute in MongoID?

I know how to do it like this:

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

but I am wondering if there is a shortcut...

2 Answers 2

12

Mongoid doesn't have the ActiveRecord style auto-created finder methods, it only supports a limited set of predefined finder 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 does have a general purpose where method so you say this:

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

where is chainable as well (just like where in newer versions of ActiveRecord) so you can add more conditions or specify the ordering by chaining more criteria calls.

Sign up to request clarification or add additional context in comments.

Comments

3

Since the version 3.0.0 of Mongoid, you can also do:

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

Contrary to where, it will raise a Mongoid::Errors::DocumentNotFound exception if the request returns no result. It's the default behavior, but if you set the raise_not_found_error configuration option to false, it will just return nil in this case.

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

1 Comment

Thanks for the "2 vs 3" doc fixes above. Even AR is moving towards find_by instead of all that nasty find_by_user_id stuff in method_missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.