gpt4 book ai didi

ruby-on-rails - Rails 网站上的 UnknownAttributeError

转载 作者:数据小太阳 更新时间:2023-10-29 08:26:19 26 4
gpt4 key购买 nike

我正在关注 tutorial关于如何创建带有评论和标签的 Ruby-on-Rails 博客网站,目前为止我的工作已放在 https://github.com/khpeek/jumpstart-blogger/ 上.

问题是,当我尝试使用如下所示的标签创建一篇新文章时,

enter image description here

我收到错误消息“ArticlesController#create 中的 ActiveRecord::UnknownAttributeError”(见下文)。

enter image description here

但是,根据教程,此时我应该期望文章“通过”。 articles_controller.rb 有一个用于 tag_list 的“设置”方法:

class ArticlesController < ApplicationController

include ArticlesHelper
def index
@articles = Article.all
end

def show
@article = Article.find(params[:id])
@comment = Comment.new
@comment.article_id = @article_id
end

def new
@article = Article.new
end

def tag_list=(tags_string)
end

def create
# fail
@article = Article.new(article_params)
@article.save
flash.notice = "Article '#{@article.title}' created."
redirect_to article_path(@article)
end

def destroy
@article = Article.find(params[:id])
@article.destroy
flash.notice = "Artice '#{@article.title}' deleted."
redirect_to articles_path
end

def edit
@article = Article.find(params[:id])
end

def update
@article = Article.find(params[:id])
@article.update(article_params)
flash.notice = "Article '#{@article.title}' updated."
redirect_to article_path(@article)
end

end

此外,“Tag”类的“to_s”方法已被修改为返回其名称:

class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings

def to_s
name
end
end

简而言之,我不明白为什么 tag_list 没有被识别为 Article 的属性。我该如何解决这个问题?

最佳答案

在你的article.rb中添加:

def tag_list=(tags_string)
# first split the tags based on "," which is coming from the form
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
# search if any particular tag is present or not, based on that assign them
new_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
self.tags = new_tags
end

此外,在 articlesController.rb 中添加:

def article_params
params.require(:article).permit(:title, :body, :tag_list)
end

希望对您有所帮助!

关于ruby-on-rails - Rails 网站上的 UnknownAttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37938825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com