Stefan Schuchlenz
Stefan Schuchlenz

Reputation: 117

Rails - combine field name with prefix

In my user model (Rails 3, devise, mongoid) I have some fields starting with a prefix:

class User
 ...

 field :usr_feature1, type: Boolean
 field :usr_feature2, type: Boolean
 field :usr_feature3, type: Boolean
 field :usr_feature4, type: Boolean

 ...
end

I need a function which allows for checking those fields for true/false like so:

def check_usr "feature_id"
  # return true if e.g. usr_feature1 is true
end

How can I "combine" a prefix with the field name passed into this function? The only solution I could come up with was to create a "check function" for every field which is cumbersome and I suspect there is an easier way to achieve this.

Upvotes: 0

Views: 125

Answers (1)

Santhosh
Santhosh

Reputation: 29144

This should do, assuming feature_id is a number

def check_usr(feature_id)
  !!self["usr_feature#{feature_id}"]
end

Upvotes: 2

Related Questions