2

I have ActiveRecord model with persisted name attribute and the virtual attribute.

class MyModel < ActiveRecord::Base
 validates :name, length: { minimum: 1 }, presence: true

 def virtual_attr=(value)
  # set something
 end

 def virtual_attr
  # get something
 end
end

In my controller I am specifying strong parameters:

  def my_model_params
    params.permit(:name, :virtual_attr)
  end

When I am trying to create/update my model, my_model_params only contains a name, whilst I know that params[:virtual_attr] has the value that I passed to the controller. It seems like it is just getting filtered out. What am I doing wrong?

alexs333
  • 12,143
  • 11
  • 51
  • 89
  • 1
    can you please post what params you are getting on console complete params hash – Deepak Mahakale Jul 26 '16 at 06:30
  • @Deepak here is params hash: `{"name"=>"New", "virtual_attr"=>{"enable"=>"false", "start"=>"false"}, "controller"=>"my_model", "action"=>"create"}`. It's all there – alexs333 Jul 26 '16 at 06:38

1 Answers1

4

According to these params

{"name"=>"New", "virtual_attr"=>{"enable"=>"false", "start"=>"false"}, "controller"=>"my_model", "action"=>"create"}

You need to change strong params to:

def my_model_params
  params.permit(:name, virtual_attr: [:enable, :start])
end
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88