用户表有'id'和'name'
礼品表有'giver_id'和'receiver_id'
profile_pictures有'user_id'和'picture_url'
用户模型:
has_one :profile_picture
has_many :gifts
ProfilePicture:
belongs_to :user
礼品型号:
belongs_to :user
我无法从数据库中拔出一次数组。数组需要按名称进行字母顺序排列。我开始时:
parties = Gift.where("giver_id = ? || receiver_id = ?", current_user.id, current_user.id)
试图倒退。我尝试让所有用户都包含个人资料图片并尝试将他们映射到Gifts数组。我无法做那件事。
感谢您的帮助。
更新: 测试数据的当前结果:
Clower, Steve
Gallipert, Jay
Gallipert, Erin
Gallipert, Jay
Gallipert, Jay
Gallipert, Linda
Gallipert, Jay
Gallipert, Erin
Gallipert, Jay
Garrent, Kara
Gallipert, Jay
Atkal, Andrew
Gallipert, Jay
Dystrom, Paul
Gallipert, Jay
Clower, Steve
Gallipert, Linda
Gallipert, Jay
Garrent, Kara
Gallipert, Jay
我需要什么:
Atkal, Andrew
Clower, Steve
Dystrom, Paul
Gallipert, Erin
Gallipert, Jay
Gallipert, Linda
Garrent, Kara
我想知道这样做的唯一方法是
答案 0 :(得分:1)
class Gift
belongs_to :giver, :foreign_key => "giver_id", :class_name => "User"
belongs_to :receiver, :foreign_key => "receiver_id", :class_name => "User"
end
gifts = Gift.where("giver_id = :id OR receiver_id = :id",:id => current_user.id).includes(:giver => :profile_picture).order('users.name').includes(:receiver => :profile_picture)
# gifts sorted by giver name
# users and profile picture are included in gifts array
使用示例:
gifts.each do |gift|
gift.giver.name # giver name
gift.giver.profile_picture.picture_url # giver picture url
gift.receiver.name # receiver name
gift.receiver.profile_picture.picture_url # receiver picture url
end
更新:
测试数据尝试此代码:
gifts = Gift.select('giver_id,receiver_id').uniq.includes(:giver => :profile_picture,:receiver => :profile_picture)
gifts.sort!{|x,y| "#{x.giver.name} #{x.receiver.name}" <=> "#{y.giver.name} #{y.receiver.name}"}
gifts.each{|g| puts "#{g.giver.name}, #{g.receiver.name}"}
输出是:
Atkal, Andrew
Clower, Steve
Dystrom, Paul
Gallipert, Erin
Gallipert, Jay
Gallipert, Linda
Garrent, Kara
不是很优雅,但很快。也许有人帮我们按SQL分类礼物。