我对RoR很新,为我正在学习的课程创建一个学生项目。我想构建一种我们在课程中没有涉及的查询类型,我知道我可以在.NET和SQL中快速完成。虽然让它实现了Ruby方式,但我还有一段时间。
我想做什么:在该用户的朋友的所有“帖子”的用户页面上显示一个列表。
“帖子”可在questions
表和用户所贡献的blurbs
表中找到。我想将UNION
这两个记录集放到一个记录集中,按照updated_at DESC进行排序。
但是表格列名不一样,这是我的观点,因为我看到的其他成功答案都取决于两者之间的列名是否相同。
在SQL中,我会写一些像(强调之类的):
SELECT b.Blurb AS 'UserPost', b.updated_at, u.username as 'Author'
FROM Blurbs b
INNER JOIN Users u ON b.User_ID = u.ID
WHERE u.ID IN
(SELECT f.friend_id FROM Friendships f WHERE f.User_ID = [current user])
ORDER BY b.updated_at DESC
UNION
SELECT q.Question, q.updated_at, u.username
FROM Questions q
INNER JOIN Users u ON q.User_ID = u.ID
WHERE u.ID IN
(SELECT f.friend_id FROM Friendships f WHERE f.User_ID = [current user])
ORDER BY b.updated_at DESC
用户模型(适用)关系是:
has_many :friendships
has_many :friends, through: :friendships
has_many :questions
has_many :blurbs
问题和Blurb模型都有belongs_to :user
在视图中,我想显示“UserPost”列和“作者”的内容。我确信这是可能的,我对ActiveRecord来说太新了,以及如何形成语句。很高兴收到一些意见或审查任何与此有关的相关链接!
最终解决方案
希望这将在Ruby UNION
问题中帮助其他人。感谢@ Plamena的投入,最终的实施结果如下:
def friend_posts
sql = "...the UNION statement seen above..."
ActiveRecord::Base.connection.select_all(ActiveRecord::Base.send("sanitize_sql_array",[sql, self.id, self.id] ) )
end
答案 0 :(得分:1)
目前Active Record缺乏工会支持。您可以使用SQL:
sql = <<-SQL
# your sql query goes here
SELECT b.created_at ...
UNION(
SELECT q.created_at
....
)
SQL
posts = ActiveRecord::Base.connection.select_all(sql)
然后你可以迭代结果:
posts.each do |post|
# post is a hash
p post['created_at']
end
答案 1 :(得分:0)
这样做的最好方法就是使用Rails的强大功能
如果您想要所有属于用户的朋友:
current_user.friends.find(id_of_friend).first.questions
这将得到某位朋友的所有问题。
现在,您似乎在多个地方都有作品(如果没有您提供的作品如何与其他地方相关联的模型,这很难想象)。你能提供吗?
答案 2 :(得分:0)
@blurbs = Blurb.includes(:user)
@blurbs.each do |blurb|
p blurb.blurb, blurb.user.username
end