【问题标题】:Rails active model serializer - attribute aliasRails 活动模型序列化程序 - 属性别名
【发布时间】:2017-11-08 05:54:51
【问题描述】:

我正在将 Angular 2 应用程序与 Rails 5.1 API 后端集成。

我的 Angular 模型中有一个带有 messagedate 属性的 Comment 模型。然而,在我的Comment 的 Rails 模型中,连同message 属性,我有ActiveRecord::Migration 通过t.timestamps 自动提供的created_atupdated_at 属性。

我正在使用 ActiveModel::Serializer 来更好地控制 API 响应,并且在我的 comment_serializer 中,我想在 GET /commentsGET /comments/:id 中的每个评论的 API 响应中包含 date 来代替 created_at等等,因此不需要更改 Angular 模型 - 假设这是正确的方法,我该怎么做?

此外,当我从 Angular 客户端添加评论时,我希望 Comment 模型中的 date 属性映射到 Rails 中相应 Comment 模型中的 created_at - 我该怎么做?

【问题讨论】:

    标签: ruby-on-rails angular active-model-serializers


    【解决方案1】:

    我认为您的序列化程序中需要这一行?

    attribute :created_at, key: :date
    

    希望对某人有所帮助。

    【讨论】:

      【解决方案2】:
      1. 我想在每个评论的 API 响应中包含日期来代替 created_at

      要实现这一点,您必须在 Serializer 中定义自定义属性。像这样

      class CommentSerializer < ActiveModel::Serializer
        attributes :id, :message, :date
      
        def date
          object.created_at
        end
      end
      
      1. 我希望将 Comment 模型中的日期属性映射到 created_at

      为此,您只需在创建评论时手动更新 created_at 字段。像这样的

      class CommentController < ApplicationController
          def create
          @comment = Comment.new(comment_params)
          @comment.created_at = params[:comment][:date]
      
          if @comment.save
              render :something
          else
              render :something
          end
      
        end
      
        private
      
        def comment_params
          params.require(:comment).permit(:message, :next_field, :etc)
        end
      end
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-04
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 2016-09-03
        • 2023-04-06
        相关资源
        最近更新 更多