Best practice for different column types in Rails

I have a model in rails that relates to a game element owned by the user. This weapon has an is_equipped column that reminds you that the item is equipped or not. Game_item can be a weapon, helmet, etc. (Set item_type in the game_item model).

Now I am looking for a good way to get an equipped item for each 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 a better way to do this, rails way :) Any ideas?

+3
source share
2 answers

You can use scopes for this.

Sort of

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

: 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

+5
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

Source: https://habr.com/ru/post/1787023/


All Articles