在模型中查找相关属性

时间:2011-08-01 19:02:22

标签: ruby-on-rails ruby ruby-on-rails-3 model

我有一个包含30个属性的模型。但这些属性可以分为两组。

例如我有:

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)
       ]

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

随意添加一些救援,但可以通过不同方式完成。

答案 2 :(得分:0)

试试这个:

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

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

答案 3 :(得分:0)

使用state_machine,这样你的逻辑就会在一个带有清晰dsl的地方。 https://github.com/pluginaweek/state_machine

相关问题