current_user的Rails关联

时间:2012-03-12 23:34:24

标签: ruby-on-rails ruby-on-rails-3 associations

我不久前读过这篇文章:http://pivotallabs.com/users/nick/blog/articles/275-advanced-proxy-usage-part-i正在谈论AR代理等。

作者指出我现在的问题是什么。

这个例子将描述它。

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

在这里

class Image
  belongs_to :user
  belongs_to :gallery
end

注意:我使用PostgreSQL

因此,当您使用图库访问我的所有图片时:Gallery.first.includes(:my_images)

如果我想要返回所有图片:Gallery.first.includes(:images)

那么现在如何将当前用户传递到has_many

中的条件

修改

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

1 个答案:

答案 0 :(得分:0)

如果我理解得很好,你想得到类似的东西:

current_user.galleries.first.images

如果是这样,您只需要通过第三个模型(可能名为UserGallery)在用户和图库之间创建一个has_many关联。

更多信息有很多,通过:

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