使用 Active Record 查询关联记录

Querying associated records using Active Record

我有一个型号Tippani,它属于另一个型号Fiscal Year

Tippani.rb

class QuotationTippani < ApplicationRecord
  belongs_to :fiscal_year
end

我有两个属于同一财政年度的 tippaniclass 实例。

我想获取属于同一财政年度的 tippani class 实例。

我试过这样的事情:

 Tippani.where(fiscal_year_id == 4)

但是我得到一个错误

undefined local variable or method `fiscal_year_id' for main:Object

另外,有没有一些查询方法,我可以在其中获取所有 tippani 实例,其财政年度小于 2073 或某个数字。

像这样:

Tippani.fiscal_year.where(year < 2074)

你需要joins

Tippani.joins(:fiscal_year).where(fiscal_years: { id: 4 })

第二个问题也可以这样处理

Tippani.joins(:fiscal_year).where("fiscal_years.year < ?", 2074)   

希望对您有所帮助!

您需要将 Hash 传递到您的查询方法中,如下所示:

QuotationTippani.where(fiscal_year_id: 4)

或者,如果您有 FiscalYear 个可用实例并且 Fiscalyear#quotation_tippanies 关联已设置:

fiscal_year.quotation_tippanies

关于year的过滤,是关于joins的使用和正确传递参数:

QuotationTippani.joins(:fiscal_year).where('fiscal_years.year < ?', 2074)

一般来说,我建议您阅读本指南:

https://guides.rubyonrails.org/active_record_querying.html

您会在这里找到所需的所有信息。

==就是比较operator。当你写:

Tippani.where(fiscal_year_id == 4)

Ruby 将 fiscal_year_id 视为标识符并尝试查找局部变量或名为 fiscal_year_id 的方法并检查它是否等于 4。所以即使你有已分配 fiscal_year_id 您正在呼叫:

Tippani.where(true) # or false

这还差得远,因为你想在数据库中计算 WHERE tippanis.fiscal_year_id = 4

Hashes in Ruby 使用 hashrockets (=>) 或冒号 (:):

# you can assign any type of key with hashrockets
{ :foo => :bar, 1 => "first", true => "yes", false => "no" }
# colons coerce the keys to symbols
{ a: 1, b: 2, c: 3, "this gets cast to a symbol": 4 }

通常首选冒号。调用方法时,只要散列是最后一个参数,就可以省略大括号。

Tippani.where({ :fiscal_year_id => 4 }) # lots of noise
Tippani.where(fiscal_year_id: 4) # better

Also, is there some query method, where I could get all the tippani instances, whose fiscal year is less than 2073 or some number.

Something like this:

Tippani.fiscal_year.where(year < 2074)

同样,这将不起作用,因为 < 是一个运算符并且计算表达式的结果是真或假。

ActiveRecord 并没有真正优雅的方式来处理 LT、GT、LTE 和 GTE 条件。所以你要么需要使用一个字符串:

Tippani.joins(:fiscal_year).where('fiscal_years.year < ?', 2074)

或使用Arel:

Tippani.joins(:fiscal_year).where(FiscalYear.arel_table[:year].lt(2074))