DRYな備忘録

Don't Repeat Yourself.

Can't mass-assign protected attributes【Rails】【Ruby】

【問題】

コントローラーの中でupdate_attributesを使ってデータの1フィールドをアップデートしたかったのだが、

Can't mass-assign protected attributes 'points'

が出る。ちなみにコントローラとメソッドの定義は以下

class PlayersController < ApplicationController
  #中略
  # POST /players/1/vote
  def vote
    @player = Player.find(params[:id])
    points = @player.points
    unless points.nil?
      points = points + 1 
    else
      points = 1 
    end 
    @player.update_attributes( :points => points )
    respond_to do |format|
      format.html { redirect_to players_url }
      format.json { head :no_content }
    end 
  end 
end

【調査】

これや

Railsのサンプルで「Can't mass-assign protected attributes」ってエラーが出た

ということで、PROJECT_ROOT/app/model/player.rbを見に行くと

class Player < ActiveRecord::Base
  attr_accessible :from, :grade, :imgurl, :info, :introduction, :kana, :name, :number, :position
end

ほんまや。pointsだけ無い。なんでかなーと思ったのだが、pointsってフィールドはそういえばあとからmigrationつかって追加したフィールドだった。参考までに、PROJECT_ROOT/db/migrate/20130212041851_add_points_to_players.rbを見に行く、

class AddPointsToPlayers < ActiveRecord::Migration
  def change
    add_column :players, :points, :integer
  end 
end

これは、コマンド

% rails generate migration AddPointsToTitles points:integer

で、つくったクラス(参考:新しいマイグレーションを追加してテーブルを変更

【解決】

と、いうことで、app/model/player.rbに、

class Player < ActiveRecord::Base
  attr_accessible :from, :grade, :imgurl, :info, :introduction, :kana, :name, :number, :position, :points
end

と、フィールドを追加

【雑感】

f:id:otiai10:20130212193135j:plain

migrateで追加したフィールドはaccessableじゃないのかぁ。たぶんrails generate migration クラス名 フィールド名:データ型 のコマンド実行するときのオプションで指定できそうな気がするけど、まあ動くからいっか