如何仅在某些条件为真时渲染属性?

例如,我想在创建操作时呈现用户的令牌属性.

推荐答案

在最新版本(0.10.x)中,您也可以这样做:

class EntitySerializer < ActiveModel::Serializer
  attributes :id, :created_at, :updated_at
  attribute :conditional_attr, if: :condition?

  def condition?
    #condition code goes here
  end
end

例如:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :username, :name, :email, :created_at, :updated_at
  attribute :auth_token, if: :auth_token?

  def created_at
    object.created_at.to_i
  end

  def updated_at
    object.updated_at.to_i
  end

  def auth_token?
    true if object.auth_token
  end
end

EDIT (Suggested by Joe Essey) :

This method does not work with latest version (100)

0.8版则更简单.你不必使用if: :condition?.相反,您可以使用以下约定来实现相同的结果.

class EntitySerializer < ActiveModel::Serializer
  attributes :id, :created_at, :updated_at
  attribute :conditional_attr

  def include_conditional_attr?
    #condition code goes here
  end
end

上面的例子是这样的.

class UserSerializer < ActiveModel::Serializer
  attributes :id, :username, :name, :email, :created_at, :updated_at
  attribute :auth_token

  def created_at
    object.created_at.to_i
  end

  def updated_at
    object.updated_at.to_i
  end

  def include_auth_token?
    true if object.auth_token
  end
end

更多细节见0.8 documentation.

Ruby-on-rails相关问答推荐

有没有一种方法可以点击一个按钮来冒泡到父元素?

Trailblazor 操作 -> 集合 :attribute(has_many 通过关联) 与填充器 -> 如何填充 Reform::Form 形式的 slugs 数组?

尽管安装并需要 pry-rails gem,但 Rails 容器内出现未定义方法‘pry’错误

Ruby/Rails 相当于 Python 的 sys.addAuditHook

如何从数组中提取值

params.permit ruby​​3.2.1 更新后 Active::Record 的未定义方法=~

Rails 将字符串与视图中的变量连接的最佳方法

Rails:如何访问 RESTful 助手?

从 Authlogic 迁移到 Devise

从 ActiveRecord 模型的集合中构建哈希

更改 form_for rails 3.1 生成的 html 表单 ID

将 Amazon SES 与 Rails ActionMailer 结合使用

从 before_action 中排除控制器

对象不支持此属性或方法 Rails Windows 64bit

如何测试自定义验证器?

在 ruby​​ on rails 中创建自定义 html 助手

设计:在注册期间禁用密码确认

has_many :通过 class_name 和 foreign_key

Rails 路由:GET 没有参数 :id

使用连接的 Ruby on Rails ActiveRecord 查询