Rails上不同列类型的最佳实践

时间:2011-01-21 22:06:21

标签: ruby-on-rails

我在rails中有一个模型,它指的是属于用户的game_item。这种武器有一个is_equipped列,类似于该物品是否装备。 game_item可以是武器,头盔等(由game_item模型中的item_type指定)。

现在,我正在寻找一种方法来获得适合各种类型的装备。我可以执行get_equipped_item(type)之类的操作并指定类型,或者get_equipped_helmet,get_equipped_weapon等。 我正在寻找更好的方法,轨道方式:)任何想法?

2 个答案:

答案 0 :(得分:5)

您可以使用scopes

这样的东西
scope :equipped, where(:is_equipped => true)
scope :helmet, where(:item_type => 'helmet')
scope :weapon, where(:item_type => 'weapon')

然后将它们用作

ModelName.equipped # => all equipped items
ModelName.helmet.equipped # => all equipped helmets

进一步阅读:http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.htmlhttp://asciicasts.com/episodes/215-advanced-queries-in-rails-3

答案 1 :(得分:0)

rails generate scaffold GameItem item_type:string is_enabled:boolean

rake db:migrate

rails console

a = GameItem.new(:item_type => "helmet", :is_enabled => true)
b = GameItem.new(:item_type => "gun", :is_enabled => false)
c = GameItem.new(:item_type => "knife", :is_enabled => true)

s = [a, b, c]

s.find_all{|item| item.is_enabled == true}

s.size // size is 2 since 2 of the items in the array have is_enabled set to true.