我有数据库充满数据,在数据库中我有像title, name, surname
这样的字段。我可以通过GET
上的/users/1.json
请求将整个记录检索为JSON。如果我只想检索该记录的名称字段,那么/users/1/name.json
可能会这样吗?
答案 0 :(得分:2)
您可以尝试以下操作:
# routes.rb
resources :users do
member do
match ':attribute_name' => "users#get_attribute_value"
end
end
# User controller
class UsersController < ApplicationController
def get_attribute_value
attribute_name = params[:attribute_name]
@user = User.where(id: params[:id])
if User.column_names.include?(attribute_name.to_s)
render json: { "#{attribute_name}" => @user.send(attribute_name) }
else
# trying to access an attribute that does not exists
end
end
end