我正在使用带有 Rails 的 Devise 进行用户登录。这一切都很好,但是,我无法让特定的重定向工作。
我是 Rails 新手,所以我做事的方法可能不正确。
本质上,举个例子,我允许用户喜欢一个帖子。但是,他们需要登录才能这样做。我在我的控制器中创建了一个名为“like”的操作,并且控制器具有设计过滤器
before_filter :authenticate_user!, :except => [:index, :show]
输入,从而显示登录页面。一旦用户登录,我想将他们重定向回他们喜欢的帖子,并调用了“喜欢”操作。
我的控制器看起来像
def like
@post = Post.find(params[:id])
@like = Like.new;
@like.user_id = current_user.id;
@like.post_id = params[:id];
respond_to do |format|
if @like.save
format.html { redirect_to @post, notice: 'You have like this post' }
format.json { head :no_content }
else
format.html { redirect_to @post, notice: 'Sorry you like was not saved }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
自然,我不能使用 after_sign_in_path_for 对路径进行硬编码
def after_sign_in_path_for(resource)
#path to somewhere
end
但我已经读到我可以使用会话变量,也许可以在上面的代码中调用它。我可以在 Rails 的哪个部分编写会话变量,因为它在控制器操作中为时已晚(因为设计在它遇到类似操作之前接管)并且我看不到如何在视图中设置它。
我的链接也看起来像
<%= link_to "Like", {:controller => :posts, :action => :like, :id => @post.id}, {:method => :post } %> |
PS 使用创建新“帖子”时的重定向工作正常,即用户登录并被重定向到新的帖子视图。
任何帮助和提示将不胜感激。
谢谢