alexs333 alexs333 - 4 months ago 20
Ruby Question

Rails strong parameters - accepting the virtual attribute

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?

Answer

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