Rails :has_many make sure one is selected -



Rails :has_many make sure one is selected -

i have installations , versions model , installation many versions. installation can create many versions , user needs select version marked default in versions database boolean datatype.

how can create sure user has selected version list of many different versions within installation screen. 1 can selected , default field of versions model changed 'yes' , other versions belong installation set 'no'

i suggest add together foreign_key :default_version_id installation model track default version instead of using entire column in version class purpose. create validation easier too. anyway, current implementation validation rule this:

class installation < activerecord::base has_many :versions validate :default_version_must_be_selected private def default_version_must_be_selected if versions.collect{|v| v if(v.default == true)}.compact.length != 1 errors.add(:base, 'one default version required' end end end

edit:

by removing default flag version , adding default_version_id installation implementation more straight forward:

class installation < activerecord::base has_many :versions belongs_to :default_version, class_name: 'version' validates_presence_of :default_version_id end

i think you'll find interacting installations default version become lot easier approach. it's association.

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

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -