2015-11-05 66 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 

(當索引控制器動作時)