【问题标题】:Finding relevant attributes in a model在模型中查找相关属性
【发布时间】:2011-08-01 19:02:22
【问题描述】:

我有一个具有 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)
       ]

【问题讨论】:

  • 你需要保存这些东西还是只获得一个 json-like/hash 表示?
  • 不只是获取表示来创建图形!

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


【解决方案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

【讨论】:

  • 如果我想排除另一个属性? attrs = self.attributes.reject{ |attr, val| attr =~ /.*_old/ } 能否将其扩展为排除 created_at、updated_at?
  • 我也可以不接受所有具有 val =false 的 attr 吗?我做了arr &lt;&lt; { :name =&gt; attr, :y =&gt; 1, :color =&gt; (self.send("#{attr}_old") == "something" ? "red" : "green") if val = true,但我得到了undefined method
  • 伴侣.. 1000 谢谢!你太棒了!
【解决方案2】:

非常简单的例子:

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

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

【讨论】:

    【解决方案3】:

    试试这个:

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

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

    【讨论】:

      【解决方案4】:

      使用 state_machine,这样您的逻辑将在一个具有清晰 dsl 的地方。 https://github.com/pluginaweek/state_machine

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-25
        • 2013-04-17
        相关资源
        最近更新 更多