0

我尝试了以下示例的解决方案:在 Rails 中,如何使用视图呈现 JSON?

但我的问题是数据库已经保存了一个 JSON 字符串,我提取了 json 字符串,然后我应该能够在视图中显示 JSON 文件。

我使用它是因为 android 平板电脑应该能够访问相同的 url,但根据其设置(通过 POST 发送)应该显示不同的 JSON 文件,然后 android 平板电脑获取 json 并使用它来配置一些选项.

所以我已经有一个完整的工作 json 文件,我正在寻找一种在视图中显示它的方法(不呈现 html 标签和其他东西)。我尝试了以下方法(是的,我添加了 respond_to :json):

# def show_json (@config is the record, @config.json_config is the actual json configuration file
@config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
   format.json
end

然后我的观点我有

#show_json.json.erb
<%= @config.config_json %>

然后我看到的 HTML(没有给出错误)

<html><head><style type="text/css"></style></head><body></body></html>

谢谢!

编辑

我正在使用导轨 3.2.3

这是我的路线(仅相关部分)

match '/events/config', to: "events#show_json", as: :show_json
resources :events do
    member do
      get :select_item
      get :category
    end
  end

然后也是控制器(部分)

respond_to :html, :json, :js
def show_json
    #terminal_id = params["mac"]
    terminal_id = "3D:3D:3D:3D:3D:3D"
    event = current_user.events.where("date(endtime) > ? AND date(starttime) < ?", Time.now.to_s, Time.now.to_s).first
    if event.nil?
      # Nothing got returned so we use the default event
      event = current_user.events.where('"default" = ?', true).first
    end
    logger.info "MAC: #{terminal_id}"
    terminal = current_user.terminals.where(serial: terminal_id).first
    logger.info "Terminal: #{terminal.attributes.inspect}"
    logger.info "#{event.attributes.inspect}"
    @config = event.et_relationships.where(terminal_id: terminal).first
    logger.info "CONFIG #{@config[:config_json]}"

    respond_to do |format|
      format.json { render json: @config[:config_json] }
    end
  end
4

1 回答 1

1

使用render

@config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
   format.json { render json: @config }
end

然后你有 path /:model/:action.json

于 2012-05-07T15:16:44.140 回答