api - Rails - How to validate the state of associated models as a state of the parent model -
i'm building api using rails backend of ember webapp. have model named 'palette' has many colors associated it. due way ember app built, deleting colors , replacing them new objects whenever palette updated. challenge if new state of colors no longer valid, have deleted old colors , cannot return original state. solution have far create transaction in our update method of palette controller throw exception if of new color creations fails or palette fails. while solution works, feels bit clunky. there more elegant solution available?
class palettescontroller < basecontroller def update activerecord::base.transaction begin palette = palette.find params[:id] palette.destroy_colors params[:palette][:colors].each |color| color.create! palette: palette, name: color[:name], cmyk: color[:cmyk], color_type: color[:color_type] end return render json: palette.errors, status: :unprocessable_entity unless palette.save! rescue return render json: { error: 'unable process request' }.to_json, status: :unprocessable_entity end render json: palette, status: 200 end end end
i think solve this, add following code palette model:
validate :all_colors_valid def all_colors_valid colors.each |color| errors.add('color', 'invalid') unless color.valid? end end
whenever save activerecord object goes through whole bunch of steps described in link below. 1 of them validate can either rails standard validations or can write own custom validations.
if object being saved has errors after validate phase save action aborted , no changes made in database.
the 2 parameters sent errors.add
name of column error , problem is. make better maybe saying of colours bad or that.
note new colours not created after validation ok. guarantees saved without error.
if want them save palette model automatically suggest in after_save
action.
http://api.rubyonrails.org/classes/activerecord/callbacks.html
Comments
Post a Comment