rico_mac
rico_mac

Reputation: 888

ensure a create action only happens once in rails

I have a method which checks to see if the current stock level of a certain product associated with a job is below zero. If the product level does fall below zero the method in question creates a comment reminding a user. I am calling the method from my controller index action.

    def check_total_quantities(job_products, job)
      job_products.each do |job_product|
        if job.not_confirmed? && job_product.product.available_quantity < 0 
          stock_reminder = job.comments.build(body: "There is a stock issue with product '#{job_product.product.title}' in job #{job.title} for client #{job.client.title}. Stock levels might be too low to use this product on this job.",
                          admin_id: job.admin.id,
                          important: true,
                          public: true)
          stock_reminder.save
          return true
        end
      end
    end

However, if I reload the page the comment gets repeated. What ways are available to me to avoid such a thing occurring? I only really want it to happen once.

Upvotes: 0

Views: 144

Answers (1)

Tiago Farias
Tiago Farias

Reputation: 3407

You can use Active Record's find_or_create_by method. So after your if condition you can check if a comment of that type for that specific job already exists, if not, save a new one (what you're doing now). You can do both steps in one command. Pretty cool.

job.find_or_create_by(job_id: job.id, type: :stock_below_zero)

I think it's necessary to have a defining attribute in comments like type or something, or a flag stock_below_zero saying if that comment is under that condition or not (or visualized or not) to differentiate between other comments for that same job.

Upvotes: 1

Related Questions