簡體   English   中英

Rails + MongoID - 按屬性查詢

[英]Rails + MongoID - Querying by attribute

我有這樣的模型:

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

我得到了:

Lesson:Class的未定義方法`find_by_user_id'

如何通過MongoID中的特定屬性進行查詢?

我知道如何這樣做:

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

但我想知道是否有捷徑......

Mongoid沒有ActiveRecord樣式自動創建的finder方法,它只支持一組有限的預定義finder方法

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

然而,它確實有一個通用的where的方法 ,所以你這樣說:

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

where是可鏈接以及(就好像where的的ActiveRecord的新版本),所以你可以添加更多的條件,或者通過鏈接多個標准調用指定的順序。

從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM