相关疑难解决方法(0)

ActiveRecord:在带有eager-loaded关联的`where`子句之后不能使用`pluck`

我有一个应用程序,有许多Post模型,每个模型都是belongs_to一个User模型.发布这些帖子时,PublishedPost会创建belongs_to相关Post模型的模型.

我正在尝试构建一个ActiveRecord查询来查找与用户名匹配的已发布帖子,然后获取这些已发布帖子的ID,但是当我尝试pluck在加载我的关联和搜索之后尝试使用该方法时出现错误他们用这个where方法.

这是(我的控制器的一部分):

class PublishedPostsController < ApplicationController

  def index
    ar_query = PublishedPost.order("published_posts.created_at DESC")

      if params[:searchQuery].present?
        search_query = params[:searchQuery]
        ar_query = ar_query.includes(:post => :user)
                           .where("users.name like ?", "%#{search_query}%")
      end

    @found_ids = ar_query.pluck(:id)

  ...

  end

end
Run Code Online (Sandbox Code Playgroud)

pluck调用该方法时,我得到了这个:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.name' in 'where clause': SELECT id FROM `published_posts`  WHERE (users.name like '%Andrew%') ORDER BY published_posts.created_at DESC
Run Code Online (Sandbox Code Playgroud)

我可以得到我正在寻找的结果

@found_ids = ar_query.select(:id).map{|r| r.id}
Run Code Online (Sandbox Code Playgroud)

但我宁愿使用,pluck …

sql activerecord arel ruby-on-rails-3

10
推荐指数
2
解决办法
5489
查看次数

如何(大规模)减少Rails应用程序中的SQL查询数量?

在我的Rails应用程序中,我users可以拥有许多invoices,反过来可以有很多payments.

现在,在dashboard视图我要汇总所有payments一个user曾经接受,要么下令按年,季度或月.该payments也分为,,和税收.

user.rb:

class User < ActiveRecord::Base

  has_many  :invoices
  has_many  :payments

  def years
    (first_year..current_year).to_a.reverse
  end

  def year_ranges
    years.map { |y| Date.new(y,1,1)..Date.new(y,-1,-1) }
  end

  def quarter_ranges
    ...
  end

  def month_ranges
    ...
  end

  def revenue_between(range, kind)
    payments_with_invoice ||= payments.includes(:invoice => :items).all
    payments_with_invoice.select { |x| range.cover? x.date }.sum(&:"#{kind}_amount") 
  end

end
Run Code Online (Sandbox Code Playgroud)

invoice.rb:

class Invoice < ActiveRecord::Base

  belongs_to :user
  has_many :items
  has_many :payments …
Run Code Online (Sandbox Code Playgroud)

ruby activerecord ruby-on-rails ruby-on-rails-3

6
推荐指数
1
解决办法
2416
查看次数

标签 统计

activerecord ×2

ruby-on-rails-3 ×2

arel ×1

ruby ×1

ruby-on-rails ×1

sql ×1