user7383466
user7383466

Reputation:

Ruby on Rails - Check if object has been changed

In my application I have models Post & Image. Both Post & Image have same columns: description, title, tags.

This is what I have in my models:

class Post < ActiveRecord::Base
  has_many :images, inverse_of: :post
  accepts_nested_attributes_for :images

class Image < ActiveRecord::Base
  belongs_to :post

I use nested_forms when a user is creating a post so they can add as many images they want under a post.

Currently when a user is creating a post, that post's description, title & tags will be added to its images (this is because of some stuff I do for users) from Post model.

This is how I am doing it.

class Post < ActiveRecord::Base
after_create :adding_details_to_images

private

  def adding_details_to_images
      self.images.each { |image| image.update_attributes(
          description: self.description,
          title: self.title,
          tags: self.tags
        )
      }
  end 

Users still can go to images#edit view and change description, title & tags individually for each image.

How can I see if each image's description, title & tags has been manually overwritten/updated or they still use/inherit post's description, title & tags?

Is it good idea/practice to make a array from Post's, description, title & tags & Image's, description, title & tags and check if they match? If so how can make as a function so I can call from model or controller?

Upvotes: 1

Views: 1971

Answers (2)

Gerry
Gerry

Reputation: 10507

This is just a variation of gabrielhilal's answer:

Is it good idea/practice to make a array from Post's, description, title & tags & Image's, description, title & tags and check if they match?

Yes, you could do it like this:

image.rb

def same_as_post?
  summary == post.summary
end

def summary
  [description, title, tags]
end

post.rb

def summary
  [description, title, tags]
end

Upvotes: 1

gabrielhilal
gabrielhilal

Reputation: 10769

If you want to make sure it was manually updated or not, I would store this information in the images table (i.e a data_from_post boolean field) and then make sure you set it correctly in both cases (callback and update endpoint).

However if you just want to know if the details are the same (user might update these fields with the same data as associated post), you could add something like the following to Image model:

def same_as_post?
  description == post.description && title == post.title && tags == post.tags
end

Upvotes: 1

Related Questions