Question

We have an action that returns a dynamic list of user emails that are due for a monthly newsletter. The action takes an optional mark_as_sent parameter, which if present will update the user records to show they were sent an email today.

But even though the update operation happens after the users have been selected, the action always returns an empty list when mark_as_sent is true.

The two operations are not part of the same transaction, so I don't understand why the first one seems to be taking effect before the second?

  def monthly_email_list

    last_month = DateTime.current-1.month
    # Grab all users who havent received a monthly follow up email in a month or more:
    @users = User.where("monthly_email_sent < '#{last_month}' AND on_mailing_list = 't'").select("email","id") 

    if params[:mark_as_sent]
      count = User.where("monthly_email_sent < '#{last_month}'").select("email","id").update_all(:monthly_email_sent => DateTime.current)
    end

  end
Was it helpful?

Solution

Rails lazy-loads data from first query, and executes second one immediately. Try to force the first query:

@users = User.where("monthly_email_sent < '#{last_month}' AND on_mailing_list = 't'").select("email","id").to_a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top