我一直在用Rails构建Web API。对于这种情况, 我需要为API定义一些资源。 所以很难弄清楚在哪里放些东西来缩小查询结果。导轨;在哪里放置查询缩小界面
我们可以在AR scope
指定东西;
class Post < ActiveRecord::Base
scope :published, -> { where(published: true) }
end
或 与class method
;
class Post < ActiveRecord::Base
def self.published
where(published: true)
end
end
和serverside resources
(I使用jsonapi-resource);
class ContactResource < JSONAPI::Resource
attributes :name_first, :name_last, :full_name
def full_name
"#{@model.name_first}, #{@model.name_last}"
end
def self.updatable_fields(context)
super - [:full_name]
end
def self.creatable_fields(context)
super - [:full_name]
end
end
什么让你决定在哪里放这些类型的查询缩小界面。 这些之间有什么区别。 (特别是class method
vs scope
很混乱。)
有什么想法吗?
如果我正确理解了jsonapi资源,它基本上只是一个将记录转换为JSON的序列化程序。因为你在上面做的是它属于模型的数据库范围。范围只是类方法的语法糖。 – max
作用域*是*类方法和[“使用类方法是接受作用域参数的首选方法。”](http://guides.rubyonrails.org/active_record_querying.html#passing-in-arguments)。所以根据官方的Rails指南,你的'published'范围应该直接作为类方法实现(即'def self.published')。 –
@max是的,这是串行器。那么何时将方法放入串行器?我想我可以将方法放入序列化程序或范围/ AR类方法来输出缩小结果。 – Tosh