Rails检索记录字段

时间:2013-12-02 18:45:08

标签: ruby-on-rails

我有数据库充满数据,在数据库中我有像title, name, surname这样的字段。我可以通过GET上的/users/1.json请求将整个记录检索为JSON。如果我只想检索该记录的名称字段,那么/users/1/name.json可能会这样吗?

1 个答案:

答案 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