ruby-on-rails - 从rails方法获取json数据

标签 ruby-on-rails ruby json ruby-on-rails-4

我想我在这里遗漏了一些愚蠢的东西,但无法弄清楚并且已经尝试了一个多小时。所以不要浪费时间..

我想使用 jsonUsers Controller 中获取 index 操作。
例如 localhost:3000/users.json 现在给我数据..

[{"id":17,"url":"http://localhost:3000/users/17.json"},{"id":16,"url":"http://localhost:3000/users/16.json"}]

但我在 User 表中还有其他属性,如 first_namelast_name 等。我想从 json 中使用它们。

我应该如何修改我现有的方法以获得所需的详细信息。

  # GET /users
  # GET /users.json
  def index
   @users = User.all
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:avatar, :first_name, :last_name)
    end

最佳答案

将索引方法更改为:

def index
 @users = User.all
 render :json => @users
end

这将在 localhost:3000/users 上显示 json

或者,如果您明确希望在 localhost:3000/users.json

上使用它

像下面这样使用respond_to:

def index 
  @users = User.all
  respond_to do |format|
     format.json { render :json => @users}
  end
end

关于ruby-on-rails - 从rails方法获取json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26053501/

相关文章:

java - 如何在 Clojure 中创建命令行可执行文件

asp.net - 如何让 ASP.NET AJAX 使用 GZip 压缩发送其 JSON 响应?

json - JQ - 格式 JSON 数组将值附加到特定值

php - JSON 编码/解码无法正常工作

ruby-on-rails - 如何将 worker 分为工作延迟+ heroku的工作池?

ruby-on-rails - 未找到 Webpacker 配置文件 - Rails 6.0.0

ruby-on-rails - 仅当 URL 中存在参数时,Rails will_paginate 使用 :conditions,

ruby - 将 ruby​​ 方法从 method() 转换为 ().method

html - 自定义 Bootstrap Forms 2.4.0 的复选框(和一般元素)

ruby-on-rails - rails : aggregate multiple models into single view (think dashboard)