hyperrjas
hyperrjas

Reputation: 10744

Can I delete an object without deleting any of its attributes?

eg.

post = Post.first

post.image_path #(this is a image path like http://localhost:3000/uploads/image/sd54asdf.jpg)

if I doing:

post.destroy

With this, I destroy every attributes from post object including the image.

Can I delete object without delete the image?

Can anyone tell me if this is possible?

With this method, I check if is the last object referenced by the image.

def validates_image_dependents
  post = self.find(params[:id])
   i=0
  for this_post in Post.all
   if this_post.posted_filename == post.post_filename
    i+=1
   end
  end
 return i > 1
end

Upvotes: 0

Views: 249

Answers (1)

Nick
Nick

Reputation: 2478

Calling destroy on a record is going to delete all data relating to that record. I think that you have 3 options:

  1. Make an associated object that contains information about the image and do not set up Rails to delete the associated records when a Post is deleted
  2. I suspect this is more like what you're trying to achieve - Instead of destroying objects you may still need to reference, update the Post model to have a boolean that tracks whether the record is "deleted" and then use this to only retrieve active posts. This is soft-deleting and is very common where complex associations make it hard to totally delete records
  3. Set up the destroy action to create some sort of archived post record that you can use to access the attributes you still require

I like option 2 but it depends on exactly what you're trying to achieve.

Upvotes: 1

Related Questions