在Mongoid has_many关系中重写发现

时间:2012-03-29 15:22:32

标签: ruby-on-rails ruby mongoid

在Rails 3.2.1上使用Mongoid 2.4.5

我有Book的模型has_many :pages

class Book
  include Mongoid::Document

  has_many :pages
end

class Page
  include Mongoid::Document

  field :page_number
  belongs_to :book
  validates_uniqueness_of :page_number, scope: :book
end

我正在使用嵌套资源,以便获取/books/4f450e7a84b93e2b44000001/pages/4f4bba1384b93ea750000003/

等网址

我希望能够使用/books/4f450e7a84b93e2b44000001/pages/3/这样的网址来获取该书中的第三页。

现在问题的症结所在: 我希望通过Book.find('4f450e7a84b93e2b44000001').pages.find('3')或类似Book.find('4f450e7a84b93e2b44000001').pages.find('4f4bba1384b93ea750000003')

之类的调用找到该页面

我知道我可以使用类似

的内容覆盖find中的Page方法
  class << self
    def find(*args)
      where(:page_number => args.first).first || super(args)
    end
  end

但这似乎对作用域查询book.pages.find('3')没有任何影响,因为范围搜索似乎使用了不同的查找方法。

如何专门覆盖book.pages.find('3')使用的查找方法?

2 个答案:

答案 0 :(得分:1)

为什么要在您的网页上执行where标准?

Book.find('4f450e7a84b93e2b44000001').pages.where( :page_number => '3')

您可以在页面

中添加范围
class Page
  scope :page_number, lambda{|num| where(:page_number => num) }
end

并使用它:

Book.find('4f450e7a84b93e2b44000001').pages.page_number('3')

答案 1 :(得分:0)

在页面模型上定义一个返回页码的to_param方法。这样,所有Rails URL帮助程序在构建URL(自动)时都会使用它。然后你可以使用像

这样的东西
@book.pages.where(:page_number => params[:page_id]) # page_id is actually the result of page#to_param

顺便说一下。我不知道你的书有多大,但从面向文档的数据库的角度来看,将书页嵌入书中可能更有意义。整个关系业务不是MongoDB的原生。