我有两个型号
class User < ActiveRecord::Base
has_many :resources
end
class Resource < ActiveRecord::Base
belongs_to :user
has_many :resource_images, :dependent => :destroy
has_many :resource_activities, :dependent => :destroy
end
控制器:
resource = Resource.where(:id => params[:id])
render :json => resource, :include => [:resource_images, :resource_activities, :user], :status => 200
是否有一种简单的方法可以过滤从用户模型返回的列?
问候。
答案 0 :(得分:0)
当然,你可以这样做:
render :json => resource, :include => {:resource_images => only: {[:id, :your_column]}, :resource_activities, :user }, :status => 200
或使用除了:
render :json => resource, :include => {:resource_images => { except: [:id, :your_column]}, :resource_activities, :user }, :status => 200
如果需要,您甚至可以包含方法:
render :json => resource, :include => { resource_images: { methods: :thumbnail}, :resource_activities, :user }, :status => 200
如果你想阅读更多内容,这里有一篇非常好的文章:https://quickleft.com/blog/keeping-your-json-response-lean-in-rails/