Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, scope, OR and joins

I have a scope:

includes(:countries).where("profiles.sector = :sector OR advices.sector = :sector", :sector => sector)

It produces the following SQL:

SELECT `profiles`.* FROM `profiles` INNER JOIN `advices` ON `advices`.`profile_id` = `profiles`.`id` WHERE (profiles.sector = 'Forestry_paper' OR advices.sector = 'Forestry_paper')

(yes I have country in my Profile and in my Country model)

Unfortunately, the OR seems to fail:

it doesn't render a profile having only the proper sector but no related advice. Thoughts?

like image 218
apneadiving Avatar asked Feb 18 '11 22:02

apneadiving


People also ask

What are scopes in Rails?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query. Example: scope :active_users, -> { where(active: true) }

What is the difference between scope and class method Rails?

Scopes are just class methods. Internally Active Record converts a scope into a class method. "There is no difference between them" or “it is a matter of taste”.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

You are doing an INNER JOIN, so it requires that the profiles have a corresponding advice. Try the following instead:

Profile
  .joins("LEFT JOIN advices ON advices.profile_id = profiles.id")
  .where("profiles.sector = :sector OR advices.sector = :sector", :sector => sector)

This will also include profiles that have no advices.

like image 67
Pan Thomakos Avatar answered Sep 19 '22 22:09

Pan Thomakos