2012-10-11 82 views
4

在我的Rails 3.2的項目,我有一個表格在app/views/sites/的Rails:訪問參數鑑於表單提交後

<%= form_for(@site) do |site_form| %> 
    ... 
    <div class="field"> 
    <%= site_form.label :hash_name %><br /> 
    <%= site_form.text_field :hash_name %> 
    </div> 
    ... 
    <div class="actions"> 
    <%= site_form.submit %> 
    </div> 
<% end %> 

然後create函數創建new.html.erb一個新的網站在sites_controller.rb

def create 
    @site = Site.new(params[:site]) 

    respond_to do |format| 
    if @site.save 
     format.html { redirect_to @site } 
    else 
     format.html { render action: "new" } 
    end 
    end 
end 

然後在用戶提交後,我想顯示用戶剛剛提交的hash_name,在show.html.erb

You just put in <%= params[:hash_name] %>. 

但訪問params[:hash_name]不起作用。我怎樣才能訪問它?

回答

3

你重定向到一個不同的動作 - 這將重置您傳遞給所有的參數創建行爲。

或者通過hash_name作爲其他答案建議的參數,或者直接從@site對象獲取它。

+0

好吧,直接從'@ site'工作。 無論如何,如何通過'hash_name'作爲參數?我嘗試了'redirect_to @site,:hash_name => params [:hash_name]',然後訪問'params [:hash_name]會產生空的。 –

+0

不需要將它作爲參數傳遞,但要做到這一點,您需要將其添加到生成的路線中,例如。 'redirect_to site_path(@site,hash_name:hash_name)'(或者你的路由被調用)。 – sevenseacat

+0

好的,謝謝! –

4

只是他們追加到選項:

redirect_to的@site,:hash_name => PARAMS [:hash_name]

+0

不,這不起作用。仍然是'params [:hash_name]'什麼也沒有。 –

+0

啊,明白了..我必須做'你只需要放入<%= @ site.hash_name%>'。 –

+0

嘗試通過@site路徑的參數。 redirect_to your_site_show_path(:hash_name => params [:hash_name]) –