2009-07-09 37 views
1

沒有人知道如何防止link_to_unless_current的失敗機制?link_to_unless_current在處理帶有錯誤消息的表單時會失敗,並且其中包含restfull路由

f.e:我有我的

link_to_unless_current "new task", new_task_path 

頁面導航當我點擊鏈接,我來到新TAKS路徑形式......不創建鏈接 - >確定。 然後我把不正確的值放在表單中並提交。

TasksController處理「創建」操作,ActiveRecord模型的驗證因數據不正確而失敗,控制器呈現「新」操作(幷包含模型的錯誤消息)。

class TasksController < ApplicationController 
    def create 
     @task = Task.new(params[:task]) 

     if @task.save 
      flash[:notice] = 'task was successfully created.' 
      redirect_to(tasks_url) 
      else 
      render :action => "new" 
     end 
    end 
end 

但是這裏鏈接被創建! - >因爲URL之間的區別:

link path = new_task_path 

posted path = tasks_path with :method => :post 

是否有人知道如何幹淨地解決這個問題?

感謝

回答

2

有一個快速瀏覽一下源link_to_unless_current ...

...它利用current_path?這樣,你應該能夠做這樣的事情:

在一個幫手...

def current_page_in?(*pages) 
    pages.select {|page| current_page?(page)}.compact.any? 
end 

...然後在您的視圖中,您可以提供上述Shadwell答案中的任何一個named_routes或哈希數組。

<%= link_to_unless(current_page_in?(new_thing_path, things_path), "add a thing") %> 

你的想法...

修訂

有一個思考這個...這會是巨大的,如果你可以只使用它就像你希望原始方法奏效。在這裏,我們將提供的命名路由(或控制器+操作哈希)與當前頁面及其引用者進行比較。

def current_page_or_referrer_in(options) 
    url_string = CGI.unescapeHTML(url_for(options)) 
    request = @controller.request 
    # We ignore any extra parameters in the request_uri if the 
    # submitted url doesn't have any either. This lets the function 
    # work with things like ?order=asc 
    if url_string.index("?") 
    request_uri = request.request_uri 
    referrer_uri = request.referrer 
    else 
    request_uri = request.request_uri.split('?').first 
    referrer_uri = request.referrer.split('?').first 
    end 

    #referrer_uri always has full path (protocol, host, port) so we need to be sure to compare apples w apples 
    if url_string =~ /^\w+:\/\// 
    ["#{request.protocol}#{request.host_with_port}#{request_uri}", referrer_uri].include?(url_string) 
    else 
    referrer_uri = referrer_uri.gsub(request.protocol, '').gsub(request.host_with_port, '') 
    [request_uri, referrer_uri].include?(url_string) 
    end 
end 

的妙處在於,它現在可以讓你只是這樣做(從你的例子):

<%= link_to_unless(current_page_or_referrer_in(new_task_path), "Add a task") %> 

它會接着顯示如果你在new_task_path或頁面,它已經發送(如創建頁面

0

您可以而不是link_to_unless_current做到這一點:

link_to_unless(controller_name == 'tasks' && 
       (action_name == 'new' || action_name == 'create'), 
       new_task_path) 
+0

大聲笑...容易容易gg – Lichtamberg 2009-07-09 14:50:41

+0

但是,是不是有一個解決方案,與命名的路線? – Lichtamberg 2009-07-09 14:51:12

相關問題