【问题标题】:Way to return True/False with rails api?使用rails api返回真/假的方法?
【发布时间】:2011-05-18 14:17:02
【问题描述】:

我需要创建一个方法,该方法由本地应用程序使用两个参数调用。那我怎么能返回真或假呢?用xml?我的方法如下所示:

def check_license
  app_id = params[:id]
  app_sn = params[:sn]

  @license = License.find_by_id(app_id)

  respond_to do |format|
    if @license.app_serial == app_sn
      # should return true here
   else
     # should return false here
   end
  end
end

提前致谢!

【问题讨论】:

    标签: ruby-on-rails xml api rest return-value


    【解决方案1】:

    我相信你可以使用:

    def check_license
      app_id = params[:id]
      app_sn = params[:sn]
    
      @license = License.find_by_id(app_id)
    
      @license.app_serial == app_sn
    end
    

    ruby 方法的最后一行将是返回值,因此这里的方法将返回最后一个关系语句的结果:true 或 false。

    如果您对所有格式都给出相同的响应,则不需要respond_to |format|,我猜您是这样,因为您返回的是布尔值。

    【讨论】:

    • 谢谢。以及如何在浏览到 url 时删除“模板丢失”错误?
    • 看我的回答。默认情况下,Rails 将 render 一个模板。您可能需要直接指示 Rails render 对象,而不是使用模板。使用render :json => value.to_json
    【解决方案2】:
      respond_to do |format|
        @license.app_serial == app_sn
       end
    

    Rails 会自动返回执行的最后一行的结果。

    【讨论】:

      【解决方案3】:
      # if you can use json:
      licensed = @license.app_serial == app_sn
      respond_to do |format|
        format.js { render :json => licensed.to_json }
      end
      

      【讨论】:

        【解决方案4】:

        您首先需要确定其他内部应用程序将调用此应用程序的格式。流行的(和理智的)格式是 xml 或 json。

        然后,在您的控制器中,您需要以每种格式呈现响应:

        resp = @license.app_serial == app_sn
        respond_to do |format|
           format.json { render :json => resp }
           format.xml do
              if resp
                head :ok
              else
                render :xml => resp, :status => 403 # that's a failed authentication response
              end
           end
        end
        

        【讨论】:

          猜你喜欢
          • 2011-02-04
          • 1970-01-01
          • 1970-01-01
          • 2016-05-10
          • 1970-01-01
          • 2014-09-07
          • 2011-05-11
          • 1970-01-01
          • 2017-11-20
          相关资源
          最近更新 更多