I'm trying to let my Rails 5 app tweet whenever a new plugin is created with the sferik/twitter gem. In the tweet I'd like to post the url to the new plugin. So in my controller I added the following:
class PluginsController < ApplicationController
include Rails.application.routes.url_helpers
def create
@plugin = current_user.plugins.build(plugin_params)
$client.update("#{url_for(@plugin)}")
end
end
With client.update
I send the tweet. The thing I'm running in though is that url_for(@plugin)
is not generating the accurate link to the new plugin. It outputs http://localhost:3000/plugins
in my tweet where it should output http://localhost:3000/plugins/does-this-work
.
When I try the same in Rails Console it does output the right link.
2.5.7 :009 > include Rails.application.routes.url_helpers
=> Object
2.5.7 :010 > url_for(@plugin)
=> "http://localhost:3000/plugins/does-this-work"
Why is the output in my controller and console not the same?
It looks like, in your controller, you haven't actually saved the plugin yet. That means that it doesn't have an id and therefore that rails can't generate the url fully.
build
creates a new plugin object with the parameters but it doesn't save it. You'd either need to add a @plugin.save
or @plugin.save!
to save it or you could use current_user.plugins.create(plugin_params)
.
I expect in your console you're creating or fetching the plugin differently which is why you're seeing different behaviour.
Arguably it would be more helpful to give you an error at that point but technically it is the url that you would POST a new plugin too which is, I think, why it is behaving like that.