1
我的設置:Rails的2.3.9,紅寶石1.8.7處理accepts_nested_attributes_for孩子的錯誤
users_controller.rb
def character
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.json { render :json => @user }
else
format.json { render :json=> @user.errors.full_messages, :status => :unprocessable_entity }
end
end
end
user.rb
accepts_nested_attributes_for :characters
has_many :characters
end
字符。 rb
belongs_to :user
before_create :check_count
def check_count
if Characters.find(:all, :conditions => ["user_id = ?", self.user_id).count == 3
errors.add_to_base I18n.t :exceeds
false
end
end
end
在用戶字符方法(這是一種自定義方法)中,我只想創建一個子字符,前提是用戶沒有3個字符。我的問題是如何從check_count方法中將錯誤消息返回給@user對象,當前錯誤引用字符對象而不是@user。在此先感謝您的幫助。
今後,請將帖子中的各個文件分開,如本文更新後的版本所示。它有助於使它們更具可讀性。 – 2011-04-09 00:48:06