Rails重定向取决于登录状态

时间:2012-07-12 22:33:33

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我的rails应用程序中有一个联系表单。现在它只是重定向到主页,无论如何。如果用户已登录,我想重定向到user_path,如果不是,我想重定向到主页..我该怎么做?

*使用设计

contact_controller

  def create
    @message = Message.new(params[:message])

    if @message.valid?
      NotificationsMailer.new_message(@message).deliver
      redirect_to(user_path, :notice => "Message was successfully sent.")
    else
      flash.now.alert = "Please fill all fields."
      render :new
    end
  end

end

2 个答案:

答案 0 :(得分:6)

如果他们已登录,您可以直接重定向到其他地方:

if current_user
    redirect_to(user_path, :notice => "Message was successfully sent.")
else
    redirect_to root_path
end

这是假设您的current_xxx设置为“user

答案 1 :(得分:0)

使用user_signed_in?帮助

def create
  @message = Message.new(params[:message])

  if @message.valid?
    NotificationsMailer.new_message(@message).deliver
    if user_signed_in?
      redirect_to user_path, :notice => "Message was successfully sent."
    else
      redirect_to root_path
    end
  else
    flash.now.alert = "Please fill all fields."
    render :new
  end
end