【问题标题】:Rails + MongoID - Querying by attributeRails + MongoID - 按属性查询
【发布时间】:2012-03-17 04:24:06
【问题描述】:

我有一个这样的模型:

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}) 

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

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    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),因此您可以添加更多条件或通过链接更多条件调用来指定排序。

    【讨论】:

      【解决方案2】:

      从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

      【讨论】:

      • 感谢上面的“2 vs 3”文档修复。甚至 AR 也在朝着 find_by 发展,而不是 method_missing 中那些讨厌的 find_by_user_id 东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多