2011-08-01 43 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