Can't mass-assign protected attributes: name, sales_date

最近ちまちまRails3の勉強をしている。その中の1つの http://www.rubylife.jp/rails/ をやっている。その時にうまく動かなかったのでメモ。rubyrailsのバージョンは以下の通り。

[k32ru@localhost]~/rubylife/sample% ruby -v
ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-linux]
[k32ru@localhost]~/rubylife/sample% rails --version
Rails 3.2.13

モデルの作成とデータベースの利用 - Ruby on Rails入門の箇所で以下のようなエラーが出た。

rake db:seed --trace
** Invoke db:seed (first_time)
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:abort_if_pending_migrations
rake aborted!
Can't mass-assign protected attributes: name, sales_date

Can't mass-assign protected attributesという検索キワードで出てきたRailsのサンプルで「Can't mass-assign protected attributes」ってエラーが出た | @ovreneli (tech)を参考にしてサンプルのapp/models/title.rbを以下のように変更した。先頭に+がある行が追加行であり、実際には+は入力しないものとする。

 vi app/models/title.rb
class Title < ActiveRecord::Base
  # attr_accessible :title, :body
 + attr_accessible :title, :body,:name,:sales_date,:timestamps, :tags_attributes
end

データは以下の通り確認できた。

[k32ru@localhost]~/rubylife/books% rails dbconsole
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from titles;
1|宇宙に行った日|2011-06-28|2013-06-15 22:21:46.914796|2013-06-15 22:21:46.914796
2|観察日記|2011-11-14|2013-06-15 22:21:46.973237|2013-06-15 22:21:46.973237

rails dbconsole.quitで終了させる。参考URL:Railsのサンプルで「Can't mass-assign protected attributes」ってエラーが出た | @ovreneli (tech)

sqlite> .quit