Firstly, the model.Model
part should be just Model
, as Model
is your class.
locked
is supposed to be a column/attribute of the Model class, although it seems is not the case judging from your error. Therefore, I'm gonna use other_column_name
as an example.
Explanation of what this is doing:
Model.where(column_name: value).first_or_initialize(other_column_name: some_value)
Model.where(column_name: value)
: gets models that satisfy the condition column_name == value
first_or_initialize
: if a model such that column_name == value was found, that one is returned. Otherwise, it initializes a model with column_name = value.
By passing other_column_name: some_value
, if the model was not found and needs to be initialized, it sets other_column_name
to some_value
but: 1) it does not update it if it was initially found and 2) it does not save the record.
The equivalent of first_or_initialize
that saves the new record would be first_or_create
but this would still not update the record if it already existed.
So, you should do something like this:
m = Model.where(column_name: value).first_or_initialize
m.other_column_name = some_value
m.save
This way, you first get a model where column_name
is value
or initialize a new one with this value if it didn't already exist. Then, you set the attribute other_column_name
to some_value
and save the model.
A one-liner alternative would be
Model.where(column_name: value).first_or_create.update(other_column_name: some_value)
However, note that if it needs to be created, this one will perform 2 queries (the insert and the update).
About the error part. It says the attribute locked does not exist on the Model record. Are these classes you created? Are you using some pre-existing project? You could try posting Model.attribute_names
and maybe your schema.rb