【问题标题】:How to create a scope to sort by FavoritePhoto id: in a has_many/through model association如何创建按 FavoritePhoto id 排序的范围:在 has_many/through 模型关联中
【发布时间】:2016-07-07 20:23:34
【问题描述】:

我有模型 Favorite_Photo、User 和 Photo

在 Heroku 控制台中:

u = User.find(1)
u.favorites.last 
=> #<Photo id: 37, user_id: 1, picture: "th.jpeg", title: "Cookies & Cream Pocky ", description: nil, photo_type: nil, location_type: nil, remote_picture_url: nil, created_at: "2016-07-07 03:04:03", updated_at: "2016-07-07 03:04:03">

如果我查询:

u = User.find(1)
u.favorite_photos.last
=> #<FavoritePhoto id: 87, photo_id: 12, user_id: 1, created_at: "2016-07-07 19:37:28", updated_at: "2016-07-07 19:37:28"> 

类用户

has_many :favorite_photos
has_many :favorites, through: :favorite_photos, source: :photo

班级照片

has_many :favorite_photos
has_many :favorited_by, through: :favorite_photos, source: :user

类收藏照片

belongs_to :user
belongs_to :photo
validates :user_id, uniqueness: { 
scope: [:photo_id],
message: 'can only favorite an item once'
} 

用户控制器

def show
  @user = User.find(params[:id])
  @favorites = @user.favorites
end

这将返回按 photo_id 排序的收藏夹列表。我想创建一个范围,它将根据FavoritePhoto id: 对收藏夹进行排序

【问题讨论】:

    标签: ruby-on-rails scope


    【解决方案1】:
    has_many :favorites, -> { order("favorite_photos.id ASC") }, through: :favorite_photos, source: :photo
    

    参考:scopes for has_many

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 2014-06-03
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多