【发布时间】: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