简体   繁体   中英

Rails Associations for current_user

I a while ago i read this article: http://pivotallabs.com/users/nick/blog/articles/275-advanced-proxy-usage-part-i which is talking about AR proxy etc..

The author pointed what is my issue now.

This example will describe it.

class Gallery
  has_many :images, :class_name => 'Image'
  has_many :my_images, :class_name => 'Image' #, :conditions => "images.user_id == current_user.id" # FIX THIS
end

and here

class Image
  belongs_to :user
  belongs_to :gallery
end

Notice: I use PostgreSQL

So when you access my all images with a gallery: Gallery.first.includes(:my_images)

If i want to return all images: Gallery.first.includes(:images)

So now how to pass the current user to the conditions in the has_many ?

Edit

User
  has_many :images
  has_many :galleries, through: :images

If i understand well, you want to get something like :

current_user.galleries.first.images

If so, you would just need to create a has_many association between User and Gallery through a third model, possibly named UserGallery.

More information on has many through :

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM