【问题标题】:Strong Parameters with API带有 API 的强参数
【发布时间】:2015-02-26 02:17:05
【问题描述】:

注意:这个问题已经回答(由我),下面的信息原来是一个红鲱鱼。我把它留在这里以防它对某人有帮助。答案见下文!

我正在将我的所有控制器升级为强参数,但我遇到了 API 控制器问题,我必须做一些时髦的时区工作。

强参数是deal_strong_params,问题似乎在于将它们作为deal_params 行中的第二个参数。我已经尝试了很多东西,比如玩弄 ActionController::Parameters.new() 的东西,但还没有做到。与强参数的情况一样,我得到 400 个错误而不是我的预期响应。我已经尝试了很多东西,我真的欢迎您的建议。

来自 API 控制器的相关代码:

before_filter :validate_update_params, :only => [:update]
.
. [show method left out]
.
def update
 deal = SuperDeal.find_by_id(params[:id])
 return head :not_found unless deal

 deal_params = convert_time_to_local(deal, deal_strong_params)

 respond_to do |format|
  format.json {
    if deal.update_attributes(deal_params)
      render :text => "Successful update", :status => :created
    else
      render :text => "Unsuccessful update: # {deal.errors.full_messages.join(", ")}", :status => :expectation_failed
     end
   }
 end
end

强大的参数:

def deal_strong_params
 params.require(:deal).permit(:offer_starts_at,:offer_ends_at,:copy_complete,:short_title, { :deal_status_attributes => [:id, :ops_complete_at] })
end

还有适用于 TimeCop 的特殊时间公式。因为我需要它,所以我包含它:

def convert_time_to_local(deal, deal_params)
 # times are coming in as UTC
 [:offer_starts_at, :offer_ends_at].each do |attribute|
   next unless deal_params[attribute]
   deal_params[attribute] = deal.timezone.parse("#{deal_params[attribute]} UTC")
 end
 deal_params
end

【问题讨论】:

    标签: api timezone nested-attributes strong-parameters timecop


    【解决方案1】:

    更新答案:事实证明,我没有包括找到答案的关键。问题出在测试中。这些特殊测试是为了确保无法更新交易。

    如果没有强参数,可以编写一个测试,将一个空的参数散列传递给更新,如果你只是测试它不会更新,只要你传入一个单独的id 来测试(尽管事后看来,最好在里面放一些东西来确保)。

    ActionController::TestCase BEFORE:

    should "return not found if it can't find the deal" do
      put :update, :id => 0, :deal => {}
      assert_response :not_found
    end
    

    使用强参数,必须在该哈希中包含某些内容。只需将其中一个属性与至少一个属性粘贴在一起即可。这实际上使它成为一个更健壮的测试,传递的比 ID 更多,但此外(正如我发现的那样),它需要强大的参数。我没有在任何地方找到此文档,我希望有一天我将它留在这里对某人有所帮助。

    ActionController::TestCase 之后:

    should "return not found if it can't find the deal" do
      put :update, :id => 0, :deal => { :copy_complete => true } #NOTE: Strong params doesn't allow an empty :deal => {}
      assert_response :not_found
    end
    

    【讨论】:

      猜你喜欢
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      相关资源
      最近更新 更多