Kurt Peek
Kurt Peek

Reputation: 57581

UnknownAttributeError on Rails website

I'm following a tutorial on how to create a Ruby-on-Rails blogging website with comments and tags, and have put my work so far on https://github.com/khpeek/jumpstart-blogger/.

The problem is that when I try to create a new article with tags as shown below,

enter image description here

I get an error message "ActiveRecord::UnknownAttributeError in ArticlesController#create" (see below).

enter image description here

However, according to the tutorial I should at this point expect the article to "go through". The articles_controller.rb has a 'set' method for 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

Further, the "to_s" method for the "Tag" class has been modified to return its name:

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

    def to_s
        name
    end
end

In short, I don't understand why tag_list is not recognized as an attribute for Article. How might I fix this?

Upvotes: 2

Views: 161

Answers (2)

Emu
Emu

Reputation: 5905

In you article.rb add:

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

Also, in articlesController.rb add:

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

Hope it helps!

Upvotes: 6

SnehaT
SnehaT

Reputation: 309

It seems you are using Rails 4. Have you included tag_list into your Strong parameter permit list?

Upvotes: 0

Related Questions