Dan*_*Dan 40 ruby-on-rails active-model-serializers
如果某些条件为真,我该如何渲染属性?
例如,我想在create action上呈现User的token属性.
Abd*_*ADI 60
你也可以这样做:
class EntitySerializer < ActiveModel::Serializer
attributes :id, :created_at, :updated_at
attribute :conditional_attr, if: :condition?
def condition?
#condition code goes here
end
end
Run Code Online (Sandbox Code Playgroud)
例如:
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
Run Code Online (Sandbox Code Playgroud)
此方法不适用于最新版本(0.10
)
随着版本,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
Run Code Online (Sandbox Code Playgroud)
上面的例子看起来像这样.
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
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参见0.8文档.
apn*_*ing 44
你可以覆盖attributes
方法,这是一个简单的例子:
class Foo < ActiveModel::Serializer
attributes :id
def attributes(*args)
hash = super
hash[:last_name] = 'Bob' unless object.persisted?
hash
end
end
Run Code Online (Sandbox Code Playgroud)
您可以首先在序列化器“初始化”方法上设置条件。此条件可以从代码中的其他任何位置传递,包括在“initialize”接受作为第二个参数的选项哈希中:
class SomeCustomSerializer < ActiveModel::Serializer
attributes :id, :attr1, :conditional_attr2, :conditional_attr2
def initialize(object, options={})
@condition = options[:condition].present? && options[:condition]
super(object, options)
end
def attributes(*args)
return super unless @condition #get all the attributes
attributes_to_remove = [:conditional_attr2, :conditional_attr2]
filtered = super.except(*attributes_to_remove)
filtered
end
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下,始终会传递 attr1,而如果条件为真,则条件属性将被隐藏。
您将在代码中的任何其他位置获得此自定义序列化的结果,如下所示:
custom_serialized_object = SomeCustomSerializer.new(object_to_serialize, {:condition => true})
Run Code Online (Sandbox Code Playgroud)
我希望这有用!
归档时间: |
|
查看次数: |
20253 次 |
最近记录: |