开发者

Where do you usually keep types in rails?

It's not a blog post, it's a question!

Speaking about types I mean that we have type value and type description. We can have different types (gender, size, color and etc) and a collection of values for each type. We have 2 choices: to keep types in database or in application.

For me to keep the whole table to store type values for each type is redundant. Another way is to store types in a single table with fields: type name, type value, type description. To keep type in db useful if you would like to modify its values from application. But mostly when I add new type I am changing application behavior.

For me the better choice is to keep types in application. I have YML configuration file like this one (in fact it's a part of SettingsLogic settings file):

types:
  gender: "male female"

Doing this way I can validate form inputs:

validates_inclusion_of :gender, :in => Settings.types.gender.split(/\s/)

As far as my application is multilingual I keep descriptio开发者_开发技巧ns in localization files:

ru:  
  types:
    gender: 
      male: "Мужской"
      female: "Женский"

To prepare a collection of choices for select I use this helper method:

def genders
  genders = []
  Settings.types.gender.split(/\s/).each do |gender|
    genders << [t("types.gender.#{gender}"), gender]
  end
  genders
end

The drawback of this approach is that I have to keep in db long type values male and female instead of sufficient m and f.

So I think about a hash now:

def genders
  genders = []
  gender_types = { :m => "male", :f => "female" }
  gender_types.each do |key, value|
    genders << [t("types.gender.#{value}"), key]
  end
  genders
end

But for now I have no answer where to keep hash like I do it with strings in configuration file. As I mentioned this hash should be accessible not only from helper method but in validations too.

So the question is wide enough: How do you keep types? What is the best or better approach?


I do something similar using hashes:

class RealtyRequest < ActiveRecord::Base
   TYPOLOGY = { 'One' => 1, 'Two' => 2, 'Three' => 3 }

   def typology
     TYPOLOGY.invert[typology_id]
   end
 end

the model is a real table and I store an integer value, then I get string value with a method.

When using collections for select, you can use the hash:

<div class="field">
  <%= f.label :typology_id %><br />
  <%= f.select :typology_id, RealtyRequest::TYPOLOGY %>
</div>

cheers,

a.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜