【问题标题】:Rails: redirect two pages backRails:将两个页面重定向回来
【发布时间】:2011-03-19 06:57:33
【问题描述】:

我正在努力解决这个问题:

假设您有两个模型,其中:

:bar has_many :foos

你有一个这样的网址:http://myapp.com/24-name-of-the-bar-to-param/foos/new

在我的网站上,此页面显示了有关用户将为其创建 foo 的 bar 的大量信息。因此,即使用户未登录,用户仍然可以看到信息。

目前,当用户登录时,用于创建新 foo 的表单位于网页的左侧。当用户未登录时,它会显示“请登录或注册”

表单详细说明了我的应用程序是如何工作的,所以我想对其进行更改,以便即使用户未登录表单也会显示,如果他们点击提交,它会将他们带到 login_path然后当他们登录时,返回提交表单的路径。

我遇到了这个问题:目前我的应用程序控制器中有一个 login_required 方法,如下所示:

    def store_location
            session[:return_to] = request.request_uri
    end
 def login_required
  unless current_user || admin?
      store_location
      flash[:notice] = "Please log in"
      redirect_to login_path and return false
  end
 end

在 foo 的创建操作上调用此登录所需操作。当我点击表单上的提交时,它会将我带到http://myapp.com/foos 而不是http://myapp.com/24-name-of-the-bar-to-param/foos/new

我认为这是因为在创建操作而不是新操作上调用了登录所需的函数。

有什么想法吗?

根据请求更新这里是控制器代码和回调:

  before_filter :find_bar, :except => [:index, :edit, :update]
  before_filter :login_required, :only => [:create]
  ssl_required :edit, :update


  def new
   @foo = Foo.new :amount =>  "0.00"
   @foos = Foo.find(:all, :conditions => ["bar_id = ?", @bar.id], :order => "created_at DESC").paginate :page => params[:page], :per_page => 10
   @foos_all = Foo.find(:all, :conditions => ["hatlink_id = ?", @hatlink.id], :order => "created_at DESC")
   @current_user = current_user
   @topfooers = User.bar_amount(@bar, nil)
   @average_foo = @bar.foos.average('amount')
  end

  def create
   @foo = @current_user.foos.build params[:foo]
   if (@bar.foos << @foo)
    flash[:notice] = "Thank you for fooing!"
    redirect_to new_bar_foo_path(@bar)
   else
    render :action => :new
   end
  end
private
  def find_bar
 @bar_id = params[:bar_id]
 return(redirect_to(categories_path)) unless @bar_id
 @bar = Bar.find(@bar_id)
  end

【问题讨论】:

    标签: ruby-on-rails session redirect


    【解决方案1】:

    如果请求是 POST 或 PUT,您可以存储引用 URL(如果存在)并重定向到该页面。比如:

    def store_location
      if request.post? || request.put?
        session[:return_to] = request.env['HTTP_REFERER']
      else
        session[:return_to] = request.request_uri
      end
    end
    

    【讨论】:

      【解决方案2】:

      在发布问题五分钟后想出一个解决方案,真是太愚蠢了。哦,好吧,这就是我所做的(并且有效)。

      在 foo 的“新”动作中,我添加了这些行

      if !current_user
          store_location
      end
      

      在登录所需的方法中我添加了这个:

      if params[:controller] == "foos" && params[:action] == "create"
                      #Took out the line for storing the location in this method.
                          flash[:notice] = "Please log in"
                      redirect_to login_path and return false
      

      【讨论】:

      • 昨天我发现设计(如果这是 current_user 来自哪里)有一个帮助方法 user_signed_in? (可能也是这样)
      猜你喜欢
      • 2021-12-20
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      相关资源
      最近更新 更多