Sunday 11 June 2017

Allow serialized attributes with unknown keys to be permitted in strong parameters.

Suppose that, we have Attempt model and we have serialized an attribute in attempt.rb like this



class Attempt < ApplicationRecord

 #==== Serializations ==================
   serialize :response

 end


Now, if you are creating attempt through strong parameters in controller -

   
   
Attempt.create(attempts_params)


And you have permitted response attribute in strong parameters like this


 def attempts_params
     params.require(:attempt).permit(:response)
 end


        OR

   

 def attempts_params
     params.require(:attempt).permit(:response => {})
 end


Above strong parameters will save response as nil or blank. In this scenario we have to permit keys of serialized attributes in strong parameter



 def attempts_params
     response_keys = params[:attempt][:response].keys
     params.require(:attempt).permit(response: response_keys)
 end

6 comments:

  1. thanks for this blog!! Learnt something new.

    ReplyDelete
  2. The article provided by you is very nice and it is very helpful to know the more information.keep update with your blog.
    Ruby on Rails Online Training Hyderabad

    ReplyDelete
  3. this is an awesome blog. thankyou very much for sharing infromation.
    visit :Ruby on Rails online training

    ReplyDelete
  4. Hi, I read you blog it's amazing & helpful content. We are providing a lot services that are base on IT & development Service. Audacity24

    ReplyDelete