【问题标题】:Rails Associations for current_usercurrent_user 的 Rails 关联
【发布时间】:2012-03-29 09:33:14
【问题描述】:

前段时间我读到了这篇文章: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

【问题讨论】:

  • 您没有描述当前用户与图库和图片的关系,因此无法回答您的问题。
  • 我会编辑问题
  • 不会是 has_many :galleries has_many :images,通过 :galleries 然后按照 Spyros 说的方式访问
  • 我要求预加载...所以它只会加载我的图像!这就是我所要求的......
  • 这个问题一直困扰着我,一直没能解决。

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


【解决方案1】:

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

current_user.galleries.first.images

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

更多信息有很多通过:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多