2012-03-17 11 views
5

によってクエリが、私はこのようなモデルがあります:Railsの属性

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 

をそして私はこのようなクエリを実行しようとしています:

@lessons_by_user = Lesson.find_by_user_id current_user.id 

そして私は取得しています:

未定義のメソッド `find_by_user_id 'forレッスン:クラス

MongoIDの特定の属性でどのようにクエリを実行できますか?

私はこのようにそれを行う方法を知っている:

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

が、ショートカットがある場合、私は疑問に思って...

答えて

9

MongoidはActiveRecordのスタイルの自動作成検索メソッドを持っていません、それだけで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

しかし、それは汎用where methodを持っていないので、あなたはこれを言う:

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

where(ただのActiveRecordの新しいバージョンでwhereのような)だけでなくチェーン可能ですので、あなたはより多くの条件を追加または複数の基準呼び出しを連鎖することにより、順序を指定することができます。

+0

驚くばかりです。本当に知って良い。 –

3

はMongoidのバージョン3.0.0以来、あなたも行うことができます:リクエストが結果を返さない場合

@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

+1

上記の「2対3」の文書の修正をありがとう。 ARでも 'method_missing'のすべての厄介な' find_by_user_id'の代わりに 'find_by'の方に移動しています。 –

関連する問題