dsuma
dsuma

Reputation: 1010

using "AND" operator in rails

I have something like this:

@photos = Photo.where(:user_id => @user.id)

I want something like:

@photos = Photo.where(:user_id => @user.id, :public => 1)

However this does not work. I cannot find how to use the "AND" operator

Upvotes: 0

Views: 78

Answers (3)

Stefan
Stefan

Reputation: 114138

Your solution should work:

Photo.where(user_id: @user.id, public: 1)

Generates a query like this (assuming MySQL and a @user.id of 5):

SELECT `photos`.* FROM `photos` WHERE ((`photos`.`user_id` = 5 AND `photos`.`public` = 1))

I suspect that public is a boolean field and depending on your database adapter, true and false can either be stored as 1 and 0 or as t and f.

Try to pass a boolean value instead and let Rails handle the conversion:

Photo.where(user_id: @user.id, public: true)

It's even easier if you set up associations and some scopes:

class User < ActiveRecord::Base
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :user
  scope :public, -> { where(public: true) }
  scope :private, -> { where(public: false) }
end

Now you can fetch a user's photos with:

@user.photos.public   # user's public photos
@user.photos.private  # user's private photos

Upvotes: 5

Damien
Damien

Reputation: 27463

Databases do not always store boolean values as 1 or 0.
So ActiveRecord normalizes that and only recognizes true and false (or nil) when using hash conditions.

All these queries are equivalent:

@photos = Photo.where("user_id = ? AND public = ?", @user.id, 1)
@photos = Photo.where(user_id: @user.id, public: true)
@photos = Photo.where(user: @user, public: true)

But it is generally preferred to write it like that:

@photos = @user.photos.where(public: true)

Upvotes: 2

franchez
franchez

Reputation: 567

Try

@photos = Photo.where("user_id = ? AND public = ?", @user_id, 1) 

Active record documentation will help you.

Upvotes: -1

Related Questions