2011-01-13 52 views
0

我對Rails很陌生,所以也許我只是缺少這樣做的「Rails方式」,但我有一個模型,稱之爲Post。我可以從規範posts/new頁面創建帖子,也可以從另一個頁面創建帖子,如home/indexRails:從兩個頁面創建

home/index我有一個form_for @post(與posts/new略有不同,但說我可以使用一個部分)。問題是,在PostController.create我無法通過新創建的對象@Post回home/index(在錯誤的情況下),因爲:

  • 如果我不指定頁面渲染,它會自動呈現posts/new
  • 我不知道調用頁面,以便將其重定向到正確調用頁面(posts/newhome/index
  • 即使我知道這(黑客請求引用或使用redirect_to :back),redirect_to的不傳回的對象,所以當從home/index
  • 調用時,@post是空的

任何幫助?感謝

編輯

也許一個可能的解決辦法是讓從請求呼叫控制器/動作,並使其回。任何方式來做到這一點?

回答

0

在理論上,你可以實現你試圖通過檢查引用者做什麼:

def create 
    @post = Post.new 

    if @post.update_attributes(params[:post]) 
    # redirect as appropriate 
    else 
    render :action => case request.referer 
     when new_post_path then "posts/new" 
     when "/" then "home/index" # assuming that home/index is the root of the site 
    end 
    end 
end 
0

要獲得引用頁,你可以做一個隱藏字段名爲redirect。您可以在控制器中使用它。

redirect_to params[:redirect] || posts_path 

你試過,你通過這篇文章的ID查詢字符串到home/index

如:/home/index?post_id=42

0

你可以找出誰通過看

request.referrer 
叫你的頁面

我不知道這是否是「rails方式」,但這是我的解決方案。

您可以在創建Post後添加路線

match home/index/(:id) => "home#index" 

,並重定向到這一點。然後在你的Home控制器index行動只是做一個

@Post = Post.find(params[:index]) if params[:index] 

你的觀點應該顯示後,如果@Post存在

我喜歡這種方法,因爲它保持它應該是所有的邏輯。在控制器中路由邏輯並在視圖中查看邏輯。