Calling a controller action from a rake task
<p>I have the following in the application controller:</p>

<pre><code>class ApplicationController &lt; ActionController::Base
  protect_from_forgery with: :exception

  def api_auth
    @api_key = Rails.application.secrets.api_key
    @api_secret = Rails.application.secrets.api_secret
    @host_id = Rails.application.secrets.host_id
    @data_type = 'JSON'

    @options = {
      body: {
        api_key: @api_key,
        api_secret: @api_secret,
        host_id: @host_id,
        data_type: @data_type
      }
    }
  end
end
</code></pre>

<p>In my controller I have...</p>

<pre><code>  before_action :api_auth
  ...
  def get_stuff
response = HTTParty.post("api_url", @options)

stuffs = response.parsed_response["stuffs"]
current_stuffs = stuff.all
stuffs.each do |w|
  #unless stuff id already exists in DB, then create it
  #what about if an attribute of a stuff is updated? How do we capture that? UUID?
  unless (current_stuffs.pluck :stuff_id).map(&amp;:to_s).include?(w["id"].to_s)
     stuff.create(stuff_id: w["id"], topic: w["topic"], start_time: w["start_time"], join_url: w["join_url"])
  end
end
</code></pre>

<p>end</p>

<p>..and the following rake task...</p>

<pre><code>desc "Heroku task to get stuff"
task :get_stuff =&gt; :environment do
  puts "Getting stuff from api..."
  session = ActionDispatch::Integration::Session.new(Rails.application)
  session.post "/posts/get_stuff"
  puts "done."
end
</code></pre>

<p>The routes is correct, and I do not get any errors when running the task. However when I run the task my DB update action is not taking place.</p>

<p>I know the action works because I have a simple button_to set up in the view that calls the same action.</p>