假设我有一个带有 returnjson
操作的 Users
Controller 。假设我想创建一个 API,这样当客户端调用该方法时,它会将用户的数据返回给客户端。例如:
https://www.example.com/returnjson?username&password
JavaScript 使用该 URL 发出 get 请求,然后 Rails 将以 JSON 格式返回用户信息。我怎样才能做到这一点?
提前致谢!
最佳答案
哦,我明白了,您只想返回参数中请求的属性。抱歉。
首先,我只会使用 show
操作来实现此目的,而不是创建一个新操作。 show
的语义目的是返回单个记录的数据,因此这是适合此作业的正确操作。
您的请求参数结构不佳 - 我会像这样构建它们
https://www.example.com/users/123?required[]=username&required[]=password
这会给你
params = {:required => ["username", "password"]}
我会这样做:
def show
@user = User.find_by_id(params[:id])
respond_to do |format|
format.html #default to standard 'render the show template'
format.js #default to standard 'render .js file' or whatever
format.json do
#filter out the ones we want
if params[:required]
hash = @user.attributes.slice(params[:required])
else
hash = @user.attributes
end
#this will automatically call `.to_json` on the thing we pass to it (`hash` in this case)
render json: hash
end
end
end
您可以在此处添加额外的安全内容,例如限制可通过 API 访问的字段。
关于javascript - Rails 中的基本 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775789/