【问题标题】:Rails 3.2.2 - Possible to add custom node to as_jsonRails 3.2.2 - 可以将自定义节点添加到 as_json
【发布时间】:2012-06-06 13:26:28
【问题描述】:

由于我目前无法按照Rails3 ActionView Template Handlers doesn't work on Production Server 使用 json 模板引擎(jbuilder 或 rabl),我想知道如何最好地更改此控制器操作以包含带有 as_json(或其他内容)的自定义节点

class Mobile::AndroidUsersController < SecureMobileUserController
  skip_before_filter :authorize, :only => :create
  respond_to :json  

  # POST /mobile_users
  # POST /mobile_users.xml
  def create
    @mobile_user = AndroidUser.find_by_auth(params[:mobile_user][:auth])
    unless @mobile_user
      @mobile_user = AndroidUser.new(params[:mobile_user])
    else
      @mobile_user.attributes = params[:mobile_user]
    end
    respond_to do |format|
      if @mobile_user.save
        format.json #Add a custom token node here
      else
:unprocessable_entity }
        format.json { render json: @mobile_user.errors, status: :unprocessable_entity }
:unprocessable_entity }
      end
    end
  end
end

我只需要添加一个名为 token 的自定义节点,它的值是通过调用 MobileUser 类的方法获得的

:token => MobileUser.next_token

【问题讨论】:

    标签: ruby-on-rails-3 json


    【解决方案1】:

    您可以像这样更改对 as_json 的调用:

    format.json {render :json => @mobile_user.as_json(:methods => [:next_token])}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      相关资源
      最近更新 更多