Reputation: 59
I have been trying to compare two objects in rails, the first is from a new record and the other is a record in the database but I have not achieved it, what I have been doing is the following:
def update
new_biological_target = params[:biological_target]
old_biological_target = BiologicalTarget.find(params[:biological_target][:id])
if new_biological_target == old_biological_target
message="Equals"
else
message="different"
end
end
What I want to compare is that if the user made any changes to the registry
Upvotes: 0
Views: 1613
Reputation: 5552
You can use ActiveModel::Dirty - changed?
biological_target = BiologicalTarget.find(params[:biological_target][:id])
message = biological_target.assign_attributes(params[:biological_target]).changed? ? "Different" : "Equals"
Upvotes: 1
Reputation: 287
As others have mentioned here, you are comparing two different types. I assume you are comparing a Hash and a BiologicalTarget.
One solution is to loop through new_biological_target, and compare the values of new_biological_target to the values in the old_biological_target record.
# can initially set message to equal
message = 'equal'
new_biological_target.each do |key, value|
# make sure the record even has the attribute, then if it does, check to see if the values are the same
if old_biological_target.has_attribute?(key) && old_biological_target.attributes[key] == value
# move to next iteration of loop because the attribute was the same as value
next
# the params you are passing either have additional keys that aren't contained in the record, so handle however you want, in this case I am saying the object is different, or the value was different for the key
else
message = 'different'
break
end
end
Upvotes: 1
Reputation: 20263
Possibly, assign_attributes. So, you could do something like:
biological_target = BiologicalTarget.find(params[:biological_target][:id])
biological_target.assign_attributes biological_target_params
biological_target.changed?
message = "Changed"
else
message = "Unchanged"
end
You'll want to make sure to process those parameters so you don't get a mass assignment error.
Upvotes: 0
Reputation: 19948
You are comparing to different types, params[:biological_target]
is, most likely, an instance of Hash
and BiologicalTarget.find
is an instance of BiologicalTarget
therefore ==
will always be false
.
You could try converting your model to a Hash of attributes, as such:
new_biological_target = params[:biological_target]
old_biological_target = BiologicalTarget.find(params[:biological_target][:id]).attributes
new_biological_target == old_biological_target # => true/false
But this is unlikely to work because the params being submitted from the form will not have created_at
, updated_at
or id
attributes, for starters.
You would be better off trying to create a new model using the params and use model validations and/or database constraints to enforce uniqueness.
Upvotes: 0