Search code examples
ruby-on-railsautocompletemass-assignment

Can't create virtual attribute for railscast #102 autocomplete


I can't get what I'm doing wrong.

I'm following instuctions from revised railscast #102.

I have model Article:

  belongs_to :category

   def category_name
      category.try(:name)
   end  

   def category_name=(name)
    self.category = Category.find_by_name(name)
   end

Category.rb:

  has_many :articles

Create_categories migration:

  def change
    create_table :categories do |t|
    t.string :name
    t.timestamps
   end
  end

Create_articles:

  def change
  create_table :articles do |t|
  t.string :name
  t.text :content
  t.integer :category_id
  t.timestamps
   end
 end

and code from _form:

   <div class="field">
    <%= f.label :category_name %><br />
   <%= f.text_field :category_name %>
  </div>

After submit I get this error:

       Can't mass-assign protected attribute :category_name

EDIT

     def create
@article = Article.new(params[:article])

respond_to do |format|
  if @article.save
    format.html { redirect_to @article, notice: 'Article was successfully created.' }

  else
    format.html { render action: "new" }
  end
end
end

My log:

     Started PUT "/articles/4" for 127.0.0.1 at 2012-10-16 00:59:44 +0300
   Processing by ArticlesController#update as HTML
   Parameters: {"utf8"=>"тЬУ", "authenticity_token"=>"YDPlS//tXg6Adl1npEEyNNBMZI0
   a7hW8bV5XFPmRre4=", "article"=>{"name"=>"112312", "category_name"=>"asdasd"}, "c
   ommit"=>"Update Article", "id"=>"4"}
    ←[1m←[35mArticle Load (0.0ms)←[0m  SELECT "articles".* FROM "articles" WHERE "
   articles"."id" = ? LIMIT 1  [["id", "4"]]
   ←[1m←[36m (0.0ms)←[0m  ←[1mbegin transaction←[0m
   ←[1m←[35mCategory Load (0.0ms)←[0m  SELECT "categories".* FROM "categories" 
 WHERE "categories"."name" = 'asdasd' LIMIT 1
  ←[1m←[36m (0.0ms)←[0m  ←[1mcommit transaction←[0m

  Redirected to http://127.0.0.1:3000/articles/4
  Completed 302 Found in 16ms (ActiveRecord: 0.0ms)

So it seems to be saving, but I don't see it in my view:

 <p>
  <b>Category:</b>
  <%= @article.category %>
 </p>

Gives me blank space.


Solution

  • For this line to work <%= f.text_field :category_name %>, add this line to Article model

    attr_accessible :category_name
    

    If you tried that already, make sure you restart the web server after you call your migrations.