Query records through its belongs_to relation in Rails
With the latest rails versions you can do:
Activity.joins(:location).where(locations: { country: "Australia" })
Beware:
- it is location (singular) in
joins(:location)
because it references thebelongs_to
relationship name - it is locations (plural) in
where(…)
because it references the table name
The latter means that if you had the following:
belongs_to :location, class_name: "PublicLocation"
the query would be:
Activity.joins(:location).where(public_locations: { country: "Australia" })
Query records through its belongs_to relation in Rails 4
Your belongs_to
association name is singular (which is correct, as it the standard) in the Part
model, but you tried to join using the pluralized association name (you tried :categories
). A common mistake; you probably got mixed up between the database naming convention, and the rails association naming convention. Try instead this:
Part.joins(:category).where('categories.name = "cars"').first
Side note:
This is not related to the question, but in case you did not already know, you can use a hash in the where clause if you like as well. It would look like:
where(categories: {name: "cars"})
And the result would be the same. In your case, it is not relevant since you're clearly passing a literal string, but it may come in handy when you're using form data, or something equally non-secure, since the hash method will properly treat the parameter as text, rather than dangerously placing it in the query as-is.
Rails find records by HABTM relation
This is what you need:
BlogPost.joins(blog_categories).where(blog_categories: { id: params[:id] })
Note that you can pass an array of ids
via params[:id]
if you need to look up multiple categories.
activerecord where clause on relation belongs_to
Case.joins(:client).where(clients: { name: 'foo' })
This query will joins the clients on the case table (eliminates the Cases without any client associated) and add the where clause "where clients.name = 'foo'"
In human language, this query does:
Get the Cases having at least one Client having the name strictly equal (case-sensitive) to 'foo'
Pay attention to the plural/singular:
in the joins/includes, use the same name as the relation is declared in the model
in the where clause, always use the pluralized version of the relation (actually the table's name)
Additionnal informations:
You can use an array of values in the where clause:
Case.joins(:client).where(clients: { id: [1,2,5] })
Difference between
.joins
and.includes
: Rails :include vs. :joins
Rails 4 where -query with has_many belongs_to -relationship, searching with specific count
Should use "companies.id"
instead of "company.id"
.
Company.joins(:users).group("companies.id").having("count(users.id)>5")
And if you want to get company with 0 users, you have to use LEFT JOIN
:
Company.joins('LEFT JOIN users ON companies.id = users.company_id').group("companies.id").having("count(users.id) = 0")
How to write where condition for Ruby ApplicationRecord belongs to relationship
You can try something as follow:
product_categories = Admin::ProductCategory.joins(:category)
.where(product_type_id: self.product_type_id)
.where(categoires: { type_id: self.category.type_id })
.where(categoires: { type_id: 4 })
And this is a nice explanation of ActiveRecord join
with belongs_to
relationship https://stackoverflow.com/a/33266583/7338180.
ActiveRecord Query for Present belongs_to ID but belongs_to Object is Nil
Following should get you telephones with user_id
present but corresponding user
object is nil
.
Telephone.left_outer_joins(:user).where("users.id is NULL AND telephones.user_id is NOT NULL")
searching records in rails include belongs_to or has_many
You can do the following:
Product.includes(:producer)
.where('products.name LIKE ? OR producers.name LIKE ?', "%#{params[:q]}%", "%#{params[:q]}%")
You can make a scope with it:
class Product < ActiveRecord::Base
scope :with_name_like, lambda { |name|
includes(:producer).where('products.name LIKE ? OR producers.name LIKE ?', "%#{name}%", "%#{name}%")
}
And use it like this:
@products = Product.with_name_like('Chair')
Rails - Get all records for has many through relationship including unassociated records
You can use single query with left join
:
res = Movie.left_joins(:favourites).where(fauvorites:{ user_id: [current_user.id, nil]}).
select(Movie.arel_table[Arel.star], "(favourites.id is null) as is_favourited_by_user")
res.first.is_favourited_by_user # 0/1
returned Movie
objects will have generated is_favorited_by_user
field that indicates if particular movie is favourited by that user.
Related Topics
Notices for Sequence After Running Migration in Rails on Postgresql Application
Rails - Pass Id Parameter on a Link_To
Does Ruby Call Initialize Method Automatically
Regex, How to Match Multiple Lines
Form_For Error Messages in Ruby on Rails
How to Implement a "Callback" in Ruby
Trouble Comparing Time with Rspec
Combine Array of Array into All Possible Combinations, Forward Only, in Ruby
How to Use Gems Not in a Gemfile When Working with Bundler
Redirect User After Log in Only If It's on Root_Path
How to Check If a Ruby Array Includes One of Several Values