我有一个应用程序,有许多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 …
在我的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)