モデルに次のセッター/ゲッターメソッドを追加しましたが、フォームを保存しようとすると、一括割り当てに関するエラーが発生します。これがどのように機能するかを理解していると、opponent_nameが見つからない場合は、データベースにエントリが追加されます。
def opponent_name
opponent.try(:name)
end
def opponent_name(name)
self.opponent = Opponent.find_or_create_by_name(name) if name.present?
end
これがコンソールログからのエラーです
Started POST "/events" for 127.0.0.1 at 2013-03-26 19:07:26 +1100
Processing by EventsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"h7OrLKeDL/9KmZeGZeO+QTWHtlUdOlaMqnoMGhYaDUU=", "event"=>{"datetime(3i)"=>"2", "datetime(2i)"=>"3", "datetime(1i)"=>"2013", "datetime(4i)"=>"00", "datetime(5i)"=>"00", "event"=>"1", "location_id"=>"7", "duration"=>"30", "arrival_time"=>"30", "opponent_name"=>"Test", "home_or_away"=>"Home"}, "commit"=>"Create Event"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = 4 LIMIT 1
Completed 500 Internal Server Error in 14ms
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: opponent_name):
app/controllers/application_controller.rb:22:in `catch_not_found'
対戦相手モデル
class Opponent < ActiveRecord::Base
has_many :events
belongs_to :team
attr_accessible :name, :team_id
validates :name, :presence => true
end
イベントモデル
class Event < ActiveRecord::Base
include PublicActivity::Model
tracked
belongs_to :location
belongs_to :opponent
belongs_to :team
belongs_to :result
has_many :availabilities, :dependent => :destroy
def opponent_name
opponent.try(:name)
end
def opponent_name(name)
self.opponent = Opponent.find_or_create_by_name(name) if name.present?
end
attr_accessible :location_id, :user_id, :datetime, :score_for, :score_against, :event,
:team_id, :home_or_away, :arrival_time, :duration, :selected_players, :date, :time, :result_id
validates :event, :location_id, :team_id, :presence => true
validates_numericality_of :team_id, :only_integer => true, :greater_than_or_equal_to =>0, :message => " needs to be set, please contact your Administrator"
#validates_numericality_of :arrival_time, :only_integer =>true, :greater_than_or_equal_to =>0, :message => " must be greater than 0 minutes", :allow_blank => true
validates :home_or_away, :presence => true, :if => :event == 1
validates :score_for, :presence => true, :if => :score_against
validates :score_against, :presence => true, :if => :score_for
EVENT_TYPES = [['Game', 1], ['Training', 2], ['Social Event', 3]]
HOME_OR_AWAY = [:Home, :Away]
end