4

has_manyActiveRecord モデルに独自の関係条件を入力したいと考えています。自分の条件でデフォルトの条件をオーバーライドしたい。

Class User < ActiveRecord::Base

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

そしてそれは生成します:

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

WHERE notifs.user_id = 1アクティブなレコード (最初の外側の括弧)の既定の状態は必要ありません。自分だけが欲しい。それを指定するにはどうすればよいですか?

4

2 に答える 2

3

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"]]
于 2017-01-20T10:14:01.307 に答える
-1

:conditions次の:finder_sqlように置き換えます。

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

ドキュメントの詳細: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many

于 2013-05-27T12:51:38.570 に答える