2016-06-21 53 views
2

我正在關注如何使用評論和標籤創建Ruby-on-Rails博客網站tutorial,並且已將我的工作放到https://github.com/khpeek/jumpstart-blogger/以上。Rails網站上的UnknownAttributeError

的問題是,當我嘗試創建一個標籤一個新的文章,如下圖所示,

enter image description here

我得到一個錯誤信息「的ActiveRecord :: UnknownAttributeError在ArticlesController#創建」(見下文) 。

enter image description here

然而,根據教程我應該在這一點上希望文章爲「經歷」。該articles_controller.rbtag_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 

此外,「to_s」的「變量」類的方法已被修改,返回它的名字:

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

    def to_s 
     name 
    end 
end 

總之,我不明白爲什麼tag_list未被識別爲Article的屬性。我該如何解決這個問題?

+0

您需要添加它作爲文章的數據庫列 - 使用遷移。您的控制器中的'def tag_list =(tags_string)'方法看起來並不像它正在做什麼,它應該可能在Article模型中。 –

回答

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

你也可以在問題中的'ArticlesController'中刪除空的'def tag_list =(tags_string)'。在article.rb中爲Article定義的'tag_list ='是'Article.new(article_params)'調用的唯一版本。 –

+0

感謝您的答案。讓'通過'的關鍵是在'article.rb'的方法定義中包含'def tag_list =(tags_string)'(而不是'def tag_list')。按照Rory O'Kane的建議,我刪除了'ArticlesController'中的空方法,並且不必包含'def article_params'(至少,不要去掉這個錯誤)。 –

+0

更正:Emu給出的'def article_params'代碼是必需的,但已經包含在'ArticlesHelper'模塊中(我沒有列出)。 –

0

看來您正在使用Rails 4.您是否已將tag_list添加到您的Strong參數許可列表中?