Reputation: 6981
I want to put a link_to
call with an argument into a controller like so (twitter
is an argument in the authorise
route):
def method
"/authorise/twitter"
...
end
I don't mind copying the authorise method to make it happen, but I don't know how to pass the twitter
argument to that method.
def authorise
user = User.from_omniauth(current_user, env['omniauth.auth'])
session[:user_id] = current_user.id
end
Any help would be great. Thanks!
UPDATE
Here's the route I'm trying to replicate in a way in the controller method:
get '/authorise/:provider/callback', to: 'sessions#authorise'
And here's the from_omniauth
method:
def self.from_omniauth(user, auth)
user.provider = auth.provider
if auth.provider == "facebook"
user.uid = auth.uid
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
elsif auth.provider == "twitter"
user.access_token = auth["credentials"]["token"]
user.access_token_secret = auth["credentials"]["secret"]
end
user.save!
end
It should be passing 'twitter'
to the auth
argument, but I get this error:
undefined method `provider' for "twitter":String
app/models/user.rb:82:in `from_omniauth'
It feels like I should be passing a hash or similar, but I can't figure out what that should be. It now feels like an oauth-specific thing.
Upvotes: 0
Views: 329
Reputation: 2795
While you can't pass arguments to a rails actions, you can, indeed pass them to methods in a controller.
Stepping back from your question, I believe you're asking how to reuse a controller method. Generally, you'd want to avoid copying a method - keeping it DRY. I would break out your authorize action into a separate method.
Your code could look like this:
def new_method
authorize_from_strategy('twitter')
end
def authozie #old method
authorize_from_strategy
end
private
def authorize_from_strategy(strategy=nil)
user = User.from_omniauth(current_user, strategy || env['omniauth.auth'])
session[:user_id] = current_user.id
end
If you wanted to use the authorize_from_strategy
method in any controller, you could move that private action to your application_controller.
Also, setting session[:user_id]
might be redundant if you're using something like devise. Devise stores your user's info in the session already, which is how you have access to current_user
.
Upvotes: 1
Reputation: 1892
You can't pass arguments for a controller action, but you can pass request params into the controller. So something like:
def method
@twitter = Your_Model.find params[:twitter]
end
Hope this helps.
Upvotes: 0