ruby on rails中activemodel序列化程序中的可选属性

时间:2015-11-05 13:21:11

标签: ruby-on-rails-4 active-model-serializers rails-api

我有两个Serializer类。在索引控制器中我想跳过加载project_products,只显示/编辑方法我想获取project_product的详细信息。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

创建序列化程序实例时可以使用“except”参数:

respond_with @projects, except: project_products

(当索引控制器动作时)