复杂的活动记录关系

问题描述 投票:0回答:1

我有几节课:

class View < ApplicationRecord
  belongs_to :user
  belongs_to :article
end

class User < ApplicationRecord
  has_many :articles
  has_and_belongs_to_many :tags
  has_many :views, through: :articles
end

class Article < ApplicationRecord
  belongs_to :user
  has_many :views
end

class Tag < ApplicationRecord
  belongs_to :user
  has_many :views
  has_and_belongs_to_many :users
  has_many :articles, through: :users
end

如果我跑步:

Tag.joins(:articles).where(tag: tag, articles: { name: name }).first

它显示了Tag中的第一条记录,但是如果我运行:

Tag.joins(:articles).where(tag: tag, articles: { name: name }).count

它显示了文章中有多少条记录。

如何获取文章而不是标签?

谢谢。

ADDED

[另一个问题-当我收到所有需要的文章时,如何按视图对它们进行排序?考虑到每条文章可能有许多View记录。

ruby-on-rails
1个回答
0
投票

这些关联并不是真的那么复杂。就是不对。

# rails g model tag name:string:uniq
class Tag < ApplicationRecord
  has_many :articles, through: :taggings
end

# rails g model tagging article:belongs_to tag:belongs_to
class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :article
end

class Article < ApplicationRecord
  has_many :tags, through: :taggings
end

has_and_belongs_to_many在理论上听起来不错,但实际上却非常受限制,因为您没有可用于直接查询联接表的模型。请改用has_many through:。将标签附加到用户而不是文章本身也没有意义。

这将使您可以使用以下条件查询标签表上带有条件的文章:

Article.joins(:tags)
       .where(tags: { name: ['ruby', 'ruby-on-rails', 'web-development'] })

这将创建WHERE tags.name IN ('ruby', 'ruby-on-rails', 'web-development'),因此查询将返回带有至少一个标签的文章。获取带有所有标签的文章稍微复杂一点,可以通过使用带有计数来完成(这实际上是一个独立的问题)。

如果要添加更多条件,只需将它们添加到示波器上:

Article.joins(:tags)
       .where(tags: { name: ['ruby', 'ruby-on-rails', 'web-development'] })
       .where("articles.title LIKE '%?%'", title)
© www.soinside.com 2019 - 2024. All rights reserved.