【问题标题】:Issues with a tag system's creation标签系统的创建问题
【发布时间】:2017-01-10 13:27:19
【问题描述】:

我正在关注this tutorial 创建一些自定义标签。我除了 AJAX 和 Foundation 部分之外的说明,因为我没有以这种方式构建我的网站。我在“标签研究”部分遇到问题,您只需单击标签即可查看有关该标签的所有帖子,Rails 告诉我以下内容:

undefined method `articles' for #<Tag:0x007f0a690eeb40>

这是我根据教程改编的文件:

article.rb

class Article < ApplicationRecord

  mount_uploader :image, ArticleUploader
  extend FriendlyId
  friendly_id :titre, use: :slugged
  has_many :taggings
  has_many :tags, through: :taggings

  def all_tags=(names)
    self.tags = names.split(',').map do |name|
      Tag.where(name: name.strip).first_or_create!
    end
  end

  def all_tags
    self.tags.map(&:name).join(", ")
  end

  def self.tagged_with(name)
   Tag.find_by_name!(name).articles # Issue comes from here
  end

end

tag.rb

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

tagging.rb

class Tagging < ApplicationRecord
  belongs_to :article
  belongs_to :tag
end

config/routes.rb

 get 'tags/:tag', to: 'articles#index', as: "tag"
 resources :articles

请问您是否需要查看其他内容

如您所见,我只是使用了在开始教程时已经存在的“文章”模型,因此我使用了“文章”而不是“帖子”,正如作者所要求的那样。我在 Google 上找不到任何相关内容,而且我现在没有使用任何 IDE,所以我不知道该怎么做..

欢迎任何帮助!

【问题讨论】:

  • Tag 模型中将您的关联has_many :tags, through: :taggings 更改为:has_many :articles, through: :taggings 并尝试。你不应该面临问题。
  • 谢谢你成功了!我知道这很明显,但我找不到错字的地方

标签: ruby-on-rails model tags


【解决方案1】:

Tag 模型中,您尝试关联tags 仅意味着您正在关联自身。所以改变你的联想

has_many :tags, through: :taggings

到:

has_many :articles, through: :taggings

并尝试。你不应该面临问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多