【问题标题】:Inherited Resources and Mongoid继承的资源和 Mongoid
【发布时间】:2011-01-28 21:33:06
【问题描述】:

有没有人成功让 Rails 3、Mongoid 和 Inherited Resources 工作?实现它的任何提示?我很想同时使用这两种宝石。

目前我遇到了:

undefined method `scoped'

关于索引操作。

谢谢!


顺便说一句,作用域问题的解决方法是像这样覆盖集合:

class CampaignsController < InheritedResources::Base

  def collection
    @campaigns ||= end_of_association_chain.paginate(:page => params[:page])
  end

end

但我正在寻找更全面的方法

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid inherited-resources


    【解决方案1】:

    如果您只使用 mongoid,您应该做的是覆盖 Inherited Resources 中的默认集合行为。默认行为是这样的:

    https://github.com/josevalim/inherited_resources/blob/master/lib/inherited_resources/base_helpers.rb#L22-24

    也就是说,以下应该可以解决问题:

    module MongoidActions
      def collection
        get_collection_ivar || set_collection_ivar(end_of_association_chain.all)
      end
    end
    
    InheritedResources::Base.send :include, MongoidActions
    

    您甚至可以将集合默认为分页并在所有页面中免费分页。

    【讨论】:

    • 谢谢何塞!!效果很好。我喜欢 Inherited Resources,我渴望尝试 Mongoid——很高兴让它们玩起来很容易。
    • 更新:现在已经合并到master了,对吧?
    【解决方案2】:

    您也可以修补 Mongoid:

    module MongoidScoped
      def scoped
        all
      end
    end
    
    Mongoid::Finders.send :include, MongoidScoped
    

    这将使inherit_resources 方法按预期工作。

    【讨论】:

      【解决方案3】:

      这是我所做的,以涵盖从 InheritedResources::Base 继承和使用 inherit_resources 语句。

      module InheritedResources
        module BaseHelpers
          def collection
            get_collection_ivar || set_collection_ivar(end_of_association_chain.all)
          end
        end
      end
      

      您通常将其放入初始化程序中(我使用 config/initializers/mongoid.rb)。

      使Mongoid 2.0.0.beta.20 和inherited_resources 1.2.1 友好。

      【讨论】:

        【解决方案4】:

        非常有用的帖子!

        如果您的控制器不能从 InheritedResource::Base 子类化,而是您必须使用类方法 inherit_resources,您将如何做到这一点,如下所示:

        class MyController < AlreadyInheritedFromController
           inherit_resources
        end
        

        上面的猴子补丁似乎在这个设置中不起作用。

        看起来关键可能是InheritedResources::Base.inherit_resources,但我不清楚覆盖此方法的正确方法。如果我在这里走错了路,请纠正。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多