2014-09-21 37 views
0

我有一個form_for幫手,爲我的Image模型創建一個對象。它看起來像這樣:如何通過使用form_for創建的rails表單傳遞附加參數?

<%= form_for :image, url: images_path do |f| %> 

    <p> 
    <%= f.file_field :file %> 
    </p> 

    <p> 
    <input type="radio" name="index" value="1">1 
    <input type="radio" name="index" value="2">2 
    <input type="radio" name="index" value="3">3 
    </p> 

    <p><%= f.submit "submit" %></p> 
<% end %> 

觀察params散列後,:文件正在按預期方式傳遞。我需要單選按鈕中的值也傳遞到這個散列中,或者至少我需要知道Image控制器的create函數中的值。我如何通過參數散列(或通過其他方式)傳遞此值?

回答

1

您可以將單選按鈕的name屬性更改爲這樣的image[index]

一個更好的方法(IMO)是使用實例變量來存儲這樣的值,因爲它可以讓你編寫代碼如f.radio_button :index

例如

class Image < ActiveRecord::Base 
    attr_accessor :index 
    # Uncomment if you're using Rails < 4, otherwise whitelist the attr in the controller 
    #attr_accessible :index 
end 

在側面,可以考慮使用表單helper像radio_button_tag,比普通的HTML好得多。

0

在你可以做一些像的form_for:

<p> 
    <%= f.radio_button_tag(:index, "1") %> 
    <%= f.label_tag(:index_1, "1") %> 
    <%= f.radio_button_tag(:index, "2") %> 
    <%= f.label_tag(:index_2, "2") %> 
    <%= f.radio_button_tag(:index, "3") %> 
    <%= f.label_tag(:index_3, "3") %> 
</p> 
相關問題