2016-11-04 103 views
1

如何將那些非模型參數傳遞給控制器​​?將非模型參數傳遞給控制器​​動作

script.rb

class Script < ActiveRecord::Base 
    attr_accessor :directory 
    attr_accessor :xmlFile 
end 

show.html.erb

<h1><%= @script.Name %></h1> 

<%= simple_form_for @script, :url => script_execute_path(script_id: @script.id) do |f| %> 
    <%= f.input :directory %> 
    <%= f.input :xmlFile %> 
    <%= f.button :submit, 'Run' %> 
<% end %> 

這裏directoryxmlFile用於取輸入,但它不是Script模型的一部分。現在我需要包含在目錄中,XMLFILE值傳遞給我的execute控制器操作

def execute 
    @script = Script.find(params[:script_id]) 
    #something like this -- @xmlFile = params[:xmlFile] 
    end 

我怎麼在這裏訪問它?

回答

3

它們確實是Script模型的一部分,因爲它們被定義爲模型的屬性。他們沒有堅持的事實是無關緊要的。

您可以從表示模型本身的參數的散列中訪問它們。您可以確定檢查請求日誌的確切名稱,您將看到參數的結構。

假設模型的名稱是Script,包含腳本屬性應該被稱爲script散列鍵,因此:

params[:script][:directory] 

請注意,Ruby沒有使用駝峯,故而得名xmlFile沒有按不按照慣例,可能會導致你的問題。名稱應該是xml_file,而不是xmlFile

+0

是的,它的工作。我什麼時候使用params [modelname] [xxx]和params [xxx]? – InQusitive

1

任意字段是不是一個模型,你可以使用Rails的獨立標籤助手的一部分,如text_field_tag

<%= simple_form_for @script, :url => script_execute_path(script_id: @script.id) do |f| %> 
    <%= text_field_tag :directory %> 
    <%= text_field_tag :xmlFile %> 
    <%= f.button :submit, 'Run' %> 
<% end %> 

如果您希望使用現有的值預填充它們,你也可以通過:

<%= text_field_tag :directory, 'some default value' %> 
1

它看起來像你實際上已經知道了。通過在您的Script模型中聲明

attr_accessor :directory 
attr_accessor :xmlFile 

您已經有效地使它們成爲模型的一部分。當對象被保存時,它們不會被保存到數據庫中。但只要對象在內存中,這些屬性就可以使用。

既然你已經有了你的視圖中定義這些屬性:通過params哈希通過params[:directory]params[:xmlFile]在控制器

<%= f.input :directory %> 
<%= f.input :xmlFile %> 

他們會提供給你。

相關問題