ruby on rails - Best practices regarding per-user settings and predefining options -



ruby on rails - Best practices regarding per-user settings and predefining options -

i want save settings users , of them 1 out of predefined list! using https://github.com/ledermann/rails-settings atm.

the setting f.e. weight_unit out of [:kg, :lb].

i don't want hardcode stuff controller or view code.

it's kind of mutual functionality, wondering: did come way of abstracting business class constants or database in dry fashion?

usually, when have store not of import info don't care query individually, store them on serialized column.

in case create new column in users table (for illustration phone call "settings").

after add together user model

serialize :settings, hash

from moment can set whatever settings, example

user.settings = {:weight_unit => :kg, :other_setting1 => 'foo', :other_setting2 => 'bar'}

and saving user.save get, in settings column, serialized data.

rails de-serialize after fetching user's record, calling user.settings, saved settings user.

to more info on serialize() refer docs: http://api.rubyonrails.org/classes/activerecord/attributemethods/serialization/classmethods.html#method-i-serialize

update1 ensure settings in predefined list can utilize validations on user model.

update2 usually, if there pre-defined values it's habit store them in constant within related model, in way have access them model (inside , outside). acceptable values not alter instance makes sense share them between all. illustration more valuable word. defining in user model:

allowed_settings = {:weight_unit => [:kg, :lb], :eyes_color => [:green, :blue, :brows, :black], :hair_length => [:short, :long]}

you can utilize both

outside model itself, doing

user::allowed_settings

inside model (in validations, instance methods or wherever want) using:

allowed_settings

ruby-on-rails ruby ruby-on-rails-4

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -