activerecord - Rails: Make a new User record, analyze the data, then create a new Hipster only if the data returns true -
i want take in user data via form, analyze of data user.rb methods. if data returns true, want create new hipster record.
i only want save hipster records, not user records. generic user records useless me.
the easiest way have single hipster model , create bunch of custom validations before saving. here current code:
hipster.rb
validate :hipster_status, :on => :create def hipster_status has_a_bike? has_a_moustache? has_skinny_jeans? unless hipster? self.errors.add("aint hipster") end end def has_a_bike? # run code see if user has bike end def has_a_moustache? # run code see if user has moustache end def has_skinny_jeans? # run code see if user has skinny jeans end def hipster? has_a_bike? && has_a_moustache? && has_skinny_jeans? end
but feels wrong have these methods in hipster model. feels weird calling hipster.hipster?
feel should creating temporary user, calling user.hipster?
if returns true, create hipster (never saving user).
but i'm having hard time visualizing new architecture. when user visits user#new page, post form user#create ? don't want create user. okay post user#create no intention of creating record?
or overthinking , should stick first version?
i agree rog's comment. if you're going have users lots of accessories or other attributes, make associated model.
if bike, mustache, , skinny jeans things you're interested in, , you're using database supports array serialization postgres, little simpler like:
class user < activerecord::base # add text column users table named accessories serialize :accessories, array def has_accessory(accessory_name) accessories.include? accessory_name end def is_hipster? has_accessory('bike') && has_accessory('mustache') && has_accessory('skinny jeans') end end
Comments
Post a Comment