开发者

Best practise for different column types on Rails

开发者 https://www.devze.com 2023-02-06 06:05 出处:网络
I have a model in rails that refers to a game_item that belongs开发者_JAVA技巧 to a user. This weapon has an is_equipped column that resembles whether the item is equipped or not. The game_item can be

I have a model in rails that refers to a game_item that belongs开发者_JAVA技巧 to a user. This weapon has an is_equipped column that resembles whether the item is equipped or not. The game_item can be a weapon, a helmet and more (specified by item_type in game_item model).

Now, i'm looking for a good way to get the equipped item for every type. I can do things like get_equipped_item(type) and specify the type, or get_equipped_helmet, get_equipped_weapon etc. I'm looking for the better way to do that, the rails way :) Any ideas ?


You can use scopes for this.

Something like

scope :equipped, where(:is_equipped => true)
scope :helmet, where(:item_type => 'helmet')
scope :weapon, where(:item_type => 'weapon')

Then use them as

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

Further reading: http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html, http://asciicasts.com/episodes/215-advanced-queries-in-rails-3


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号