【问题标题】:Rails Joining together multiple tablesRails 将多个表连接在一起
【发布时间】:2014-10-02 21:16:11
【问题描述】:

所以我正在尝试创建各种新闻提要,但我不确定如何进行查询。

我有一个用户模型、一个关注位置模型和一个关注用户模型。然后我有一个 cmets 模型。我需要从用户关注的用户那里获取所有 cmets,从用户关注的位置获取所有 cmets,我必须将它们放在一起。

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

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

cmets 模型看起来像这样,它是多态的,可以发布到位置和事件

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

【问题讨论】:

  • 发布一小段代码来演示您的模型是如何定义的,这将大大有助于更准确地回答这个问题。
  • 您的 cmets 与其他元素的关系如何?它们是多态的,还是您将位置 cmets 和用户 cmets 作为不同的模型?
  • 我将根据您刚刚提供的型号信息对我的答案进行更正。

标签: sql ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

以下是模型关联的外观:

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 实例方法来收集给定用户关注的所有项目(位置或用户)。现在您可以收集单个用户关注的用户/位置的所有 cmets,如下所示:

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

这将为一个用户(包括位置和其他用户)收集所有关注的项目,获取他们所有 cmets 的列表,然后将它们展平为一个简单的数组。如果您想对它们进行排序,例如我的创作,请将其添加到末尾:

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

有一些方法可以优化这一点,但此时您可能只想专注于了解概念。

更新:

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

https://github.com/rubycuts/so26169791

【讨论】:

  • 我这样做并尝试使用该代码,但它不起作用它为我提供了一个未定义的方法 `cmets' 用于 nil:NilClass 错误。使用代码行 @user = User.find(params[:user_id]) @items = @user.followed_items.map(&:cmets).flatten
  • 我快速创建了一个 Rails 4 应用程序来测试我给你的代码,它可以工作。我在上面的答案末尾添加了指向 github 存储库的链接。请检查您的代码以确保您准确地实施了我的建议,并告诉我它是如何进行的。
  • 是的,我的代码与您的代码完全相同,但它仍然为我提供了 nil:NilClass 的未定义方法 `cmets'
  • 你能粘贴你的followed_items方法吗?这就是你的错误的根源。
  • 抱歉,我想我知道问题所在。您有 FollowedUser 或 FollowedLocation 记录,其中 follow_id 或 location_id 为 nil,或指向不存在的记录。这是一个数据完整性问题。您可以通过说“user.followed_items.compact.map(&:cmets).flatten”来快速修复它,但它是一种创可贴的解决方案。您需要找到损坏的连接记录。
猜你喜欢
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多