2015-11-05 55 views
0

我有以下两个Serializer类。在索引控制器中,我想跳过加载project_products,只显示/编辑我想要获取project_product的详细信息的方法。ruby​​ on rails中activemodel序列化程序的可选属性

class ProjectSerializer < ActiveModel::Serializer 
     attributes :id, :name, :category, :project_category_id, :status, :description 
     has_many :project_products 
    end 

class ProjectProductSerializer < ActiveModel::Serializer 
    attributes :id, :name, :quantity 
end 

控制器:

def index 
    respond_with @projects 
    end 

def load_projects 
    @projects = current_organization.projects.includes(:project_category) 
    end 
+0

综上所述,您不想在show/edit中加载project_products? – Defoncesko

+0

嗨@Defoncesko正好在我想要加载project_products在显示/编辑,但不是索引 – Santi

+0

请显示您的意见和控制器代码。 – Defoncesko

回答

0

尝试重写关联方法

class ProjectSerializer < ActiveModel::Serializer 
     attributes :id, :name, :category, :project_category_id, :status, :description 
     has_many :project_products 

    def project_products 
     if current_page?(edit_path_url) 
      object.comments 
     else 
      object.comments = nil 
    end 

end 
+0

感谢您的帮助,但是当我把代码'respond_with @projects.to_json(:except => [“project_products”])'忽略我的活动序列化器并显示所有字段形成项目表 – Santi

+0

这就是你正在使用的? https://github.com/rails-api/active_model_serializers – Defoncesko

+0

是的,你是对的 – Santi

0

创建串行实例时,您可以使用 “除” 参数:

respond_with @projects, except: project_products 

(当索引控制器动作时)