我有一个叫做标签的 Rails 类:
class Tag < ActiveRecord::Base
attr_accessor :is_enabled_on_item # a virtual attribute for ouptutting json
我想像下面这样调整 is_enabled_on_item:
t.each { |tmp| tmp.is_enabled_on_item=true if current_tag_ids.include?(tmp.tagid) }
喜欢:
[
{
tagid:1,
phrase: "blue",
is_enabled_on_item: true
},
{
tagid:2,
phrase: "yellow",
is_enabled_on_item: false
}
]
我试过收集
t.collect { |tmp| tmp.is_enabled_on_item=true if current_tag_ids.include?(tmp.tagid) }
但它返回 [true, false]
。我将如何实现我想要的?
编辑#1
我希望它返回一个标签数组。
这样的事情是可行的,但中间的 arr
似乎是不必要的:
arr=[]
t.each do |tmp|
tmp.is_enabled_on_item=current_tag_ids.include?(tmp.tagid)
arr << tmp
end
arr
最佳答案
t.map do |tmp|
tmp.attributes.merge(is_enabled_on_item: current_tag_ids.include?(tmp.tagid))
end
关于ruby-on-rails - 遍历数组,调整虚拟属性并返回具有调整值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619886/