2011-08-01 37 views
1

我有一个包含30个属性的模型。但这些属性可以分为2组。查找模型中的相关属性

比如我有:

string:title 
string:text 
... 

string:title_old 
string:text_old 
... 

我希望能够:当我在同一时间检查title属性检查title_old属性。我可以执行一个循环,如果我做了15个字符串数组或我应该写硬编码的if语句

最终目标:

 [ 
      { 
      :name => :title, 
      :y => 1 (constant), 
      :color=> red, (if title_old == "something" color = red else color = green) 
      }, 
      { 
      :name=> :text, 
      :y => 1 (constant) 
      :color => red (if text_old == "something" color = red else color = green) 
      }, 
      .... (all other 13 attributes) 
     ] 
+0

最终目标是什么? – kain

+0

编辑了问题 – glarkou

+0

你需要保存这些东西或者只是得到类似json/hash的表示? – kain

回答

1

模型:

class MyModel < AR::Base 
    def attributize 
    attrs = self.attributes.except(:created_at, :updated_at).reject{ |attr, val| attr =~ /.*_old/ && !val } 
    attrs.inject([]) do |arr, (attr, val)| 
     arr << { :name => attr, :y => 1, :color => (self.send("#{attr}_old") == "something" ? "red" : "green") } 
    end 
    end 
end 

使用:

my_object = MyModel.last 
my_object.attributize 
+0

非常感谢您的时间:) – glarkou

+0

如果我想排除其他属性? 'attrs = self.attributes.reject {| attr,val | attr =〜/.*_old/}'你能否扩展它以排除created_at,updated_at? – glarkou

+0

@ntenisOT,已更新 – fl00r

0

试试这个:

[ 
:title, 
.., 
.. 
:description 
].map do |attr| 
    { 
    :name => attr, 
    :y => 1 (constant), 
    :color=> (read_attribute("#{attr}_old") == "something") ? "red" : "green" 
    } 
end 

PS:命名属性text是一个坏主意。

1

很简单的例子:

class MyModel 
    def identify_color 
    if send("#{name}_old".to_sym) == "something" 
     'red' 
    else 
     'green' 
    end 
    end 
end 

MyModel.all.collect do |instance| 
    attrs = instance.attributes 
    attrs.merge!('color' => identify_color) 
    attrs 
end 

随意添加一些救助,但它可以以不同的方式来完成。

+0

谢谢你的伴侣:) – glarkou