2013-05-27 32 views
3

我想在我的ActiveRecord模型中输入我自己的has_many关系的条件。 我要我的条件为覆盖的默认条件。如何覆盖rails中关系的默认has_many条件?

Class User < ActiveRecord::Base 

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

并生成:

NOTIF负荷(在0.2ms)SELECT notifs * FROM notifs WHERE notifsuser_id = 1 AND((notifs.user_id = 1或notifs.user_id = 0))

我不希望活动记录的默认状态(第一WHERE notifs.user_id = 1外括号)。我只想要我自己的。我如何指定?

回答

1

为Rails 4.1+可以使用unscope关联范围内。

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"]]