繁体   English   中英

Rails将多个表连接在一起

[英]Rails Joining together multiple tables

因此,我尝试创建各种新闻提要,但不确定如何进行查询。

我有一个用户模型,一个用于关注位置的模型以及一个用于关注用户的模型。 然后我有一个评论模型。 我需要获取用户关注的用户的所有评论以及用户关注的位置的所有评论,我必须将它们放在一起。

我不太熟悉如何在sql或rails中执行此操作。 谁能将我链接到我可能会找到该方法的文章或文档?

如果您需要更多信息,请评论我还应该包括什么,因为我不确定要在帖子中包括什么。

评论模型如下所示,它是多态的,可以发布到位置和事件

create_table :comments do |t|
  t.text :text
  t.integer :user_id
  t.integer :commentable_id
  t.string :commentable_type

然后有两个单独的表供关注用户和关注位置使用

create_table :followed_locations do |t|
  t.integer :user_id
  t.integer :location_id

create_table :followed_users do |t|
  t.integer :user_id
  t.integer :followed_id

以下是模型关联的外观:

class User < ActiveRecord::Base
    has_many :comments, as: :commentable
    has_many :followed_locations
    has_many :followed_users

    def followed_items
        followed_locations.map(&:location).flatten + followed_users.map(&:followed).flatten
    end
end

class Location < ActiveRecord::Base
    has_many :comments, as: :commentable
end

class FollowedUser < ActiveRecord::Base
    belongs_to :user
    belongs_to :followed, class_name: 'User'
end

class FollowedLocation < ActiveRecord::Base
    belongs_to :user
    belongs_to :location
end

class Comment < ActiveRecord::Base
    belongs_to :commentable, polymorphic: true
end

上面的代码定义了所有模型之间的关系,并添加了一个User实例方法来收集给定用户遵循的所有项目(位置或用户)。 现在,您可以收集单个用户关注的用户/位置的所有注释,如下所示:

user.followed_items.map(&:comments).flatten

这将为用户(位置和其他用户)收集所有跟随的项,获得他们所有评论的列表,然后将它们展平为一个简单的数组。 如果您想对它们进行排序,则以我的创作为例:

user.followed_items.map(&:comments).flatten.sort_by(&:created_at)

有多种方法可以对此进行优化,但是此时,您可能只想专注于简化概念。

更新:

我创建了一个实现此解决方案的简单Rails 4应用,并将其发布在github上:

https://github.com/rubycuts/so26169791

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM