【问题标题】:Optional attribute in activemodel serializer in ruby on railsruby on rails 中 activemodel 序列化程序中的可选属性
【发布时间】:2015-11-05 13:21:11
【问题描述】:

我有以下两个序列化程序类。在索引控制器中,我想跳过加载 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

【问题讨论】:

  • 总结一下,你不想在 show/edit 中加载 project_products 吗?
  • 嗨 @Defoncesko 正好相反,我想在显示/编辑中加载 project_products 但不在索引中
  • 请显示您的视图和控制器代码。
  • def index respond_with @projects end
  • 响应格式为json

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


【解决方案1】:

尝试覆盖关联方法

 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

【讨论】:

  • 感谢您的帮助,但是当我放置代码 respond_with @projects.to_json(:except =&gt; ["project_products"]) 时,它会忽略我的活动序列化程序并显示项目表中的所有字段
  • 您是否尝试过覆盖关联方法并在内部选择您需要在路径条件下返回的内容?
  • 只是我想在列出项目时从项目表中获取一些字段。并希望项目详细信息页面中的产品列表以及项目详细信息(不是所有字段)。显然使用 activeModelSerializer
【解决方案2】:

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

respond_with @projects, except: project_products

(当索引控制器动作时)

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 2011-07-05
    • 2023-03-29
    • 1970-01-01
    • 2014-04-30
    • 2016-07-14
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多