我已將以下setter/getter方法添加到我的模型,但每當我嘗試並保存表單時,我都會收到有關批量分配的錯誤。從我的理解,這應該是如何工作的,如果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
你的模型的其餘部分是什麼樣的?您是否使用attr_accessible列出了必要的列(包括opponent_name)? – pdoherty926 2013-03-26 08:16:27
'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 – 2013-03-26 09:20:28
當我添加:opponent_name我得到'ActiveRecord :: UnknownAttributeError(未知屬性:opponent_name):' – 2013-03-26 09:22:26