`app/apis/v1/customers.rb`
module V1
class Customers < Grape::API
resource :customers, desc: "客户相关" do
add_desc "客户列表"
get do
present current_store.store_customers, with: ::Entities::Customer, type: :default
end
add_desc "客户详情"
get ":id", requirements: { id: /[0-9]*/ } do
present StoreCustomer.find(params[:id]), with: ::Entities::Customer, type: :full
end
end
end
end
那么我们再来看看对应的显示层。
app/apis/entities/customer.rb
module Entities
class Customer < Grape::Entity
expose :age, if: {type: :default} #客户列表显示(对应的type)
expose :phone_number, if: {type: :full} #客户详情显示(对应的type)
expose :name #客户列表,客户详情都会显示
expose(:login_name, if: {type: :default}) {|model|model.phone_number} #自定义expose显示的名称,判断加在()里。
end
end
NOTE: expose(:xx) 等同于官网给出的块的形式。
route_param :customer_id do
resource :girls do
end
end
# 对应的路由为 xx/customers/{customer_id}/girls
module V1
class Customer < Grape::API
get do
customer_params
present current_store.store_customers, with: ::Entities::Customer
end
def customer_params
"hello"
end
end
end
# 有报错为undefined local variable or method `customer_params'
如若将 方法转换成类方法呢?
你去试试吧
module V1
class Customer < Grape::API
get do
customer_params
present current_store.store_customers, with: ::Entities::Customer
end
helpers do
def customer_params
"hello"
end
end
end
end
发现加上 helpers 还是有点爱的。
declared(params, include_missing: false)
用这个写呀写呀的。。
declared(params, include_missing: false).slice(:name, :age)
#这样取出需要的参数
最后测试发现,报错 ActiveModel::ForbiddenAttributesError。 因为 strong_params 的安全机制。 不过也不是不可以,他提供了一个 gem 去解决这个情况:
Additionally, if the version of your Rails is 4.0+ and the application uses the default model layer of ActiveRecord, you will want to use the hashie-forbidden_attributes gem. This gem disables the security feature of strong_params at the model layer, allowing you the use of Grape's own params validation instead.
def customer_params
customer = ActionController::Parameters.new(params)
customer.permit(:name, :age)
end
grape-doc: http://www.rubydoc.info/github/intridea/grape-entity/Grape 不是之处,欢迎各位不吝指出。