我想将带有参数的link_to
调用放入控制器中,这样(twitter
是authorise
路由中的参数):
def method
"/authorise/twitter"
...
end
我不介意复制authorize方法来实现它,但我不知道如何将twitter
参数传递给该方法。
def authorise
user = User.from_omniauth(current_user, env['omniauth.auth'])
session[:user_id] = current_user.id
end
任何帮助都会很棒。谢谢!
更新
这是我试图在控制器方法中复制的路径:
get '/authorise/:provider/callback', to: 'sessions#authorise'
这是from_omniauth
方法:
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
应该将'twitter'
传递给auth
参数,但是我收到此错误:
undefined method `provider' for "twitter":String
app/models/user.rb:82:in `from_omniauth'
感觉我应该传递一个哈希或类似的东西,但我无法弄清楚应该是什么。它现在感觉像是特定于oauth的东西。
答案 0 :(得分:1)
虽然您无法将参数传递给rails操作,但您确实可以将它们传递给控制器中的方法。
退出你的问题,我相信你在问如何重用控制器方法。通常,您希望避免复制方法 - 保留它DRY。我会将你的授权操作分解为一个单独的方法。
您的代码可能如下所示:
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
如果要在任何控制器中使用authorize_from_strategy
方法,可以将该私有操作移动到application_controller。
另外,如果您使用类似设计的东西,设置session[:user_id]
可能是多余的。设计已在会话中存储您的用户信息,这是您访问current_user
的方式。
答案 1 :(得分:0)
您无法传递控制器操作的参数,但您可以将请求参数传递给控制器。如下所示:
def method
@twitter = Your_Model.find params[:twitter]
end
希望这有帮助。