简体   繁体   English

在Ruby on Rails中重构模型方法

[英]Refactoring Model Methods in Ruby On Rails

A common idiom that my camp uses in rails is as follows: 我的阵营在铁轨中使用的常用习语如下:

def right_things(all_things, value)
    things = []
    for thing in all_things
       things << thing if thing.attribute == value
    end
    return things
end

how can I make this better/faster/stronger? 我怎样才能让这更好/更快/更强?

thx 谢谢

-C -C

def right_things(all_things, value)
    all_things.select{|x| x.attribute == value}
end

If your things are ActiveRecord models and you only need the items selected for your current purpose, you may, if you're using Rails 2.0 (? definitely 2.1) or above, find named_scope s useful. 如果您的东西是ActiveRecord模型,并且您只需要为当前目的选择的项目,那么如果您使用Rails 2.0(?绝对是2.1)或更高版本,您可能会发现named_scope很有用。

class Thing
  named_scope :rightness, lambda { |value| :conditions => ['attribute = ?', value] }
end

So you can say 所以你可以说

Thing.rightness(123)

, which is (in this case) similar to ,(在这种情况下)类似于

Thing.find_by_attribute(123)

in that it boils down to a SQL query, but it's more easily chainable to modify the SQL. 因为它归结为一个SQL查询,但它更容易链接来修改SQL。 If that's useful to you, which it may not be, of course... 如果那对你有用,那可能不是,当然......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM