0

In my Rails / Angular app I am passing data to the front-end via Rails serializers, and permitting updates to fields via params.permit.

I understand that part of the purpose of the serializer/safe_params is to carefully control what comes and goes to the server. However, for most models, I am finding I need to include all fields.

Is there a metaprogramming or other method where the body of the serailizer and safe_params can simple expose / accept all fields on the model, including virtual fields?

Example code

serializer

class BatchSerializer < ActiveModel::Serializer
  attributes :id,
        :description,       
        :details,          
        :user_id,             
        :name,                
        :dataset,             
        :dataset_id,          
        :pairs_per_sequence,  
        :pairs_per_bp,         
        :batch_type,           
        :overlap_size,        
        :padding,             
        :assembly_id,          
        :multiplex_tolerance,  
        :run_id,                
        :snp_mask,             
        :primer3_parameter_id, 
        :specificity_check,
        :batch_status,
        :avoid_cross_primers,
        :temperature_similarity,
        :gibbs_free_energy,
        :base_termination,
        :wet_lab
end

controller safe_params

 def safe_params
params.permit(:id,
        :description,       
        :details,          
        :user_id,             
        :name,                
        :dataset,             
        :dataset_id,          
        :pairs_per_sequence,  
        :pairs_per_bp,         
        :batch_type,           
        :overlap_size,        
        :padding,             
        :assembly_id,          
        :multiplex_tolerance,  
        :run_id,                
        :snp_mask,             
        :primer3_parameter_id, 
        :specificity_check,
        :avoid_cross_primers,
        :temperature_similarity,
        :gibbs_free_energy,
        :base_termination,
        :wet_lab_result)
  end

EDIT

This post offers an answer to half of the problem: permit all Rails 4 Strong parameters : permit all attributes?

So how would I automatically serialize all fields?

Community
  • 1
  • 1
port5432
  • 5,889
  • 10
  • 60
  • 97
  • You could (re)define the `as_json` method to define which attributes you want serialized on the model when `to_json` is called. – Nathan Aug 31 '15 at 02:56

1 Answers1

1

If you simply stop passing in a serializer, Rails will use the default serializer that renders all attributes by default.

eg, suppose you have a model called MyObject, you can render with:

render :json => my_object

re: permitting all attributes - you can take a look at Rails 4 Strong parameters : permit all attributes? for that.

Community
  • 1
  • 1
Taryn East
  • 27,486
  • 9
  • 86
  • 108