关于如何使用评论和标签创建Ruby-on-Rails博客网站tutorial之后,我已将我的工作放在https://github.com/khpeek/jumpstart-blogger/上。
问题在于,当我尝试使用如下所示的标签创建新文章时,
我在ArticlesController中创建了一条错误消息" ActiveRecord :: UnknownAttributeError#create" (见下文)。
然而,根据教程,我应该在这一点上期望文章能够经历"。 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
此外,&#34; to_s&#34; &#34; Tag&#34;的方法class已被修改为返回其名称:
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings
def to_s
name
end
end
简而言之,我不明白为什么tag_list
未被识别为Article
的属性。我该如何解决这个问题?
答案 0 :(得分:6)
在你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
希望它有所帮助!
答案 1 :(得分:0)
您似乎正在使用Rails 4.您是否已将tag_list包含在Strong参数许可列表中?