Railsで子テーブルのスコープを使うヘ(^o^)ノ
例えばこんな感じのモデル
class User < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :user scope :published, -> { where(published: true) } end
公開中のPostを取得する場合はこんな感じですよね?
$ Post.published
んじゃ、ユーザの公開されているPostを取得する場合は?
$ User.joins(:posts).where(posts: {published: true})
イマイチですねー
そこでActiveRecord::SpawnMethodsのmergeメソッドですよ
$ User.joins(:posts).merge(Post.published)
ぶっちゃけどっちでも良いのですが...
class User < ActiveRecord::Base has_many :posts scope :published_post, -> { joins(:posts).where(posts: {published: true}) } end
merge使わないと、こんなムダscope作りたくなるのでmergeをオススメです。
Happy Hacking ٩( ‘ω’ )و