加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails MongoID – 按属性查询

发布时间:2020-12-16 23:12:51 所属栏目:百科 来源:网络整理
导读:我有这样的模型: 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 vali
我有这样的模型:
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

我得到了:

undefined method `find_by_user_id’ for Lesson:Class

如何通过MongoID中的特定属性进行查询?

我知道如何这样做:

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

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

解决方法

Mongoid没有ActiveRecord样式自动创建的finder方法,它只支持一组有限的 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中那样),这样你就可以通过链接更多的条件调用来添加更多条件或指定排序.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读