I assume that you refer to closing a topic.
I’d either use the API for that or the corresponding method on the Topic type:
Topic.where(closed: false, category_id: <catid>, id: <tid>).find_each do |topic|
topic.update_status("closed", true, Discourse.system_user)
end
Edit: I just realize that locking posts is something different. You can set the post.locked_by_id but I guess you’re not creating a logged staff action in that case.