我想我在这里遗漏了一些愚蠢的东西,但无法弄清楚并且已经尝试了一个多小时。所以不要浪费时间..
我想使用 json 在 Users
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_name
和 last_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/