Benjamin Crouzier
Benjamin Crouzier

Reputation: 41965

How to override the default has_many condition for a relation in rails?

I would like to enter my own condition for a has_many relationship in my ActiveRecord model. I want my condition to override the default condition.

Class User < ActiveRecord::Base

  has_many :notifs, :conditions => 
   proc { "(notifs.user_id = #{self.id} OR notifs.user_id = 0)" }

And it generates:

Notif Load (0.2ms) SELECT notifs.* FROM notifs WHERE notifs.user_id = 1 AND ((notifs.user_id = 1 OR notifs.user_id = 0))

I don't want the default condition of active record (the first WHERE notifs.user_id = 1 outside parens). I want only my own. How do I specify that ?

Upvotes: 4

Views: 1141

Answers (2)

droptheplot
droptheplot

Reputation: 628

For rails 4.1+ you can use unscope inside the association scope.

class Post
  belongs_to :user
end

class User
  has_many :posts, -> { unscope(:where).where(title: "hello") }
end

User.first.posts
# => SELECT "posts".* FROM "posts" WHERE "posts"."title" = $1  [["title", "hello"]]

Upvotes: 4

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41965

Replace :conditions with :finder_sqllike so:

has_many :notifs, 
  :finder_sql => proc { "(notifs.user_id = #{self.id} OR notifs.user_id = 0)" }

More details in the documentation: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many

Upvotes: -1

Related Questions