Querying associated records using Active Record

Related searches

I have a model Tippani, which belongs to another model Fiscal Year.

Tippani.rb

class QuotationTippani < ApplicationRecord
  belongs_to :fiscal_year
end

I have two instances of tippani class, that belong to the same fiscal year.

I want to get the instances of tippani class that belongs to the same fiscal year.

I tried something like this:

 Tippani.where(fiscal_year_id == 4)

But I get an error

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

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)

You need to pass Hash into your query method, like this:

QuotationTippani.where(fiscal_year_id: 4)

or, if you have FiscalYear instance available and Fiscalyear#quotation_tippanies association is set up:

fiscal_year.quotation_tippanies

About the filtering by year, it's about using joins and passing parameters properly:

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

Generally speaking, I advice you to read this guide:

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

You'll find all the information you need here.

Active Record Query Interface - Rails Edge Guides, How to use method chaining to use multiple Active Record methods together. associated records of the objects returned by Model.find using as few queries as � Active Record Query Interface. This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to: Find records using a variety of methods and conditions; Specify the order, retrieved attributes, grouping, and other properties of the found records

== is the comparison operator. When you write:

Tippani.where(fiscal_year_id == 4)

Ruby treats fiscal_year_id as an identifier and tries to find either a local variable or a method named fiscal_year_id and checks if it is equal to 4. So even if you had assigned fiscal_year_id you're calling:

Tippani.where(true) # or false

Which isn't even close since you want evaluate WHERE tippanis.fiscal_year_id = 4 in the database.

Hashes in Ruby use hashrockets (=>) or colons (:):

# 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 }

Colons are generally preferred. When you call a method you can omit the braces as long as the hash is the last argument.

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)

Again this won't work since < is an operator and the result of evaluating the expression is true or false.

ActiveRecord does not really have an elegant way of handling LT, GT, LTE and GTE conditions. So you either need to use a string:

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

Or use Arel:

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

Active Record Query Interface, Find records using a variety of methods and conditions. Specify the order, retrieved attributes, grouping, and other properties of the found records. Use eager loading to reduce the number of database queries needed for data retrieval. Use dynamic finders methods. The SRV record is a Domain Name System (DNS) resource record that is used to identify computers that host specific services. SRV resource records are used to locate domain controllers for Active Directory. To verify SRV locator resource records for a domain controller, use one of the following methods. DNS Manager

You need joins

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

Second question also can be handled in similar way.

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

Hope that helps!

ActiveRecord find associated records of associated records in one , Use a has_many through association: class Author < ActiveRecord::Base has_many :books has_many :chapters, through: :books end. And then use it like: Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent applications, since the query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.

Caching counters with ActiveRecord's counter caches, Instead of counting the associated records in the database every time Requesting the blog's index results in N+1 queries, as ActiveRecord� Up until now, we’ve covered the bread and butter you need to build basic queries using Active Record. After building a handful of projects and working through the tutorial, you should be comfortable making these queries. Active Record is much more powerful than just simple CRUD actions on individual records.

Active Record Queries, You can join tables manually or query using associations set up by Rails. You can return lists of records or perform basic math like counts and averages. Active Record takes care of building the query to avoid injection attacks, and will convert from the ruby type to the database type where needed. Elements are inserted into the string in the order in which they appear.

Now you may get two records back if you made a comment on a forum_topic with an id of 1 and a news article with an id of 1 using your query::joins => "INNER JOIN forum_topics ON forum_topics.id = comments.commentable_id"

Comments
  • In your FiscalYear model do you have has_many quotationtippanis ?
  • Yes, I do have that.
  • I would really recommend that you learn the language first before trying to learn Rails.
  • *where(fiscal_years: { id: 4 })