How to add an additional virtual attribute to wrap_parameters

I have a model with some virtual attributes, and they are included in my form and passed to the controller, but I can not force the virtual attributes (SKU) to wrap inside the model hash

{"name"=>"Productname", "description"=>"Description", "sku"=>"ak0001", "product"=>{"name"=>"Productname", "description"=>"Description"}} 

I can use the wrap_parameters parameters to overwrite it, but I would have to add all the attributes (virtual and non-virtual attributes) to the array, can I just add virtual attributes to the existing wrap parameter?

 wrap_parameters Product, :include => [:sku, :name, ..etc...] 
+7
ruby-on-rails
source share
2 answers

I had the same problem, I did not find a great solution, but I found one that seems a little better. By default, the rails will try to determine the associated model and call wrap_parameters with this model, so in your case

 wrap_parameters Product 

What exactly is the same as

 wrap_parameters Product, include: Product.attribute_names 

So, if you want to add a virtual attribute, you can just do

 wrap_parameters Product, include: Product.attribute_names + [:sku] 
+4
source share

Still have not found good solutions. So far, instead of using the wrap_parameters parameters, I overwrite the allowed_pairs

  def permitted_params { :product => params.require(:product).merge( { sku: params[:sku], } ).permit(*permitted_product_attributes) } end 
+1
source share

All Articles