[英]Rails: call link_to in a controller
我想将带有参数的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
任何帮助都会很棒。 谢谢!
UPDATE
这是我要在controller方法中以某种方式复制的路由:
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特定的东西。
虽然您无法将参数传递给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。
同样,如果您使用的是诸如devise之类的东西,则设置session[:user_id]
可能是多余的。 Devise已经在会话中存储了用户的信息,这就是您访问current_user
。
您不能为控制器操作传递参数,但可以将请求参数传递给控制器。 所以像这样:
def method
@twitter = Your_Model.find params[:twitter]
end
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.