Rails: dynamically iterate over params hash parameters to make sure they exist

I have a form with a fairly small number of parameters passed to the controller for processing. The various "sets" of parameters are called in the same way:

setname1_paramname
setname1_paramname2

Now I need to check one of these β€œsets” to make sure all fields are sent. Right now, I am doing this with an If or style statement:

if setname1_paramname.blank? || setname1_paramname2.blank? || ...etc
  @object.errors.add_to_base("All setname1 fields are required.").
  render :action => 'new'
  return false
end

Is there a way to programmatically loop over these parameters and add them to @object errors?

Thank!

+3
source share
5 answers

, , , params, , - ? , params . :

params.each do |key, value| 
   # target groups using regular expressions
   if (key.to_s[/setname1.*/])
     # whatever logic you need for params that start with 'setname1'
     if param[key].blank?
       @object.errors.add_to_base("All setname1 fields are required.").
     end
   end
end
+9

, Rails .

class SomeModel < ActiveRecord::Base
  VIRTUAL_ATTRIBUTES = [:billing_address, :billing_state, :something_else]
  attr_accessor *VIRTUAL_ATTRIBUTES
  validates_presence_of *VIRTUAL_ATTRIBUTES
  …
end
+6

, , , ?

+1

, , , hash , , ? params , , params . , , , ?

0
0

Source: https://habr.com/ru/post/1787796/


All Articles