如何从Rails查询对象访问数据?

时间:2015-04-17 21:50:41

标签: ruby-on-rails

我按照这个(https://robots.thoughtbot.com/active-record-eager-loading-with-query-objects-and-decorators)教程来构建我的查询对象,但是如何从结果中访问我的商店数据???

我得到以下对象,我去了结果= StoreWithRecentDeals.new(store:Store.all)

查询对象https://gist.github.com/jianbo/4125f3203005358e99f5

然后我想得到我的商店并从这个对象交换数据,当我去结果。我得到的商店 ArgumentError:参数个数错误(2个为1)

这是我的代码

class StoreWithRecentDeals
    def initialize(stores:)
      @stores = stores.order(created_at: :desc).limit(5)
      @deal_cache = build_deal_cache
    end

    def stores
      @stores.map { |store| StoreWithLatestDeals.new(store, @deal_cache) }
    end

    private

    def build_deal_cache
      deals.group_by(&:store_id)
    end

    def deals
      Deal.
        select("*").
        from(Arel.sql("(#{ranked_deals_query}) AS ranked_deals")).
        where("deal_rank <= 3")
    end

    def ranked_deals_query
      Deal.where(store_id: @stores.map(&:id)).select(<<-SQL).to_sql
        deals.*,
        dense_rank() OVER (
          PARTITION BY deals.store_id
          ORDER BY deals.created_at DESC
        ) AS deal_rank
      SQL
    end
  end

  class StoreWithLatestDeals < SimpleDelegator
    def initialize(store, deals_by_store_id)
      super(store)
      @deals_by_store_id = deals_by_store_id
    end

    def latest_deals
      @deals_by_store_id[id] || []
    end
  end

1 个答案:

答案 0 :(得分:0)

我猜你的问题是,你在班级StoreWithRecentDealsstores作为实例变量名称以及方法名称。

我建议给你的方法另外一些名字:

def fetch_stores
  @stores.map { |store| StoreWithLatestDeals.new(store, @deal_cache) }
end