这让我有点头疼,但我发现我把一切都错了。我提出的解决方案绝对不是最好的解决方案,可能会被重写,但它有效,现在就足够了。
对 rspec 片段的更改是创建由符号 :newpoints 表示的哈希
it "should find Points and return object" do
put :update, :username => "tester", :newpoints => {"experience_points" => 10, "shame_points" => 15, "gold" => 0}, :format => :xml
end
在控制器中处理这个请求需要一些调整,但这里是相关的部分:
class PointsController < ApplicationController
#before_filter :authenticate, :only => :update
before_filter :must_specify_user
before_filter :fix_params
before_filter :clean_up
respond_to :html, :xml, :json
def fix_params
if params[:points]
params[:points][:user_id] = @user.id if @user
end
end
def clean_up
@newpoints = params[:newpoints]
@experience = @newpoints["experience_points"]
@shame = @newpoints["shame_points"]
@gold = @newpoints["gold"]
@xp = @experience.to_i
@sp = @shame.to_i
@cash = @gold.to_i
end
def update
points = Points.find_by_user_id(@user.id, params[:id])
xp = points.experience_points
sp = points.shame_points
cash = points.gold
final_experience = xp += @xp
final_shame = sp += @sp
final_gold = cash += @cash
final_points = {:experience_points => final_experience, :shame_points => final_shame, :gold => final_gold}
if_found points do
respond_to do |format|
if points.update_attributes!(params[final_points])
format.json { head :ok }
format.xml { head :ok }
else
format.json { render :nothing => true, :status => "401 Not Authorized"}
format.xml { render :nothing => true, :status => "401 Not Authorized"}
end
end
end
end
end
显然,可以做很多事情来使这个遵循 DRY 和什么不是,所以仍然欢迎任何建议。提前致谢!