【问题标题】:Customizing has_many, belongs_to nested associations json in Active Model Serializer在 Active Model Serializer 中自定义 has_many、belongs_to 嵌套关联 json
【发布时间】:2016-11-28 10:12:15
【问题描述】:

我该怎么做

class UserSerializer < ApplicationSerializer
  attributes :id, :name. :email

  has_many :posts do                   # I don't want to use PostSerializer
    attributes :id, :title             # /posts/index would show more data
    has_many :comments do              # like created_at, updated_at, edits, other assocs..
      attributes: :id, :content
    end
  end

  belongs_to :category do              # I dont' want to user CategorySerializer
    attributes :id, :name              # /categories/index would show more data
  end                                  # like created_at, no. of users, associations, etc.,
end

【问题讨论】:

    标签: json ruby-on-rails-5 active-model-serializers rails-api


    【解决方案1】:

    你可以这样做,但使用serializers

    class UserSerializer < ApplicationSerializer
      attributes :id, :name, :email, :user_posts
    
      def user_posts
        object.posts.map do |post|
          PostSerializer.new(post, only: [:id, :title])
        end
      end
    
    end
    

    【讨论】:

    • NameError: undefined local variable or method 'user_posts'。它不跳转到函数中,事实上,它甚至不识别函数声明。我在Rails 5.0.0.1 上使用Ruby 2.3Active Model Serializers 0.10.3
    • 使用:user_posts 有助于跳转到函数中,但不尊重only: [:id, :title]
    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多