2012-08-23 22 views
0

這裏是我_form.html.erb部分的那一刻,但我想它的元素,基於第一(區)下拉選擇更新我做:如何預先填充表單(ajax方式)從其中的下拉列表中執行選擇,Ruby on Rails?

<%= form_for(@setting) do |f| %> 
    <div class="form"> 

    <div class="fieldBlock"> 
    <%= f.label :region%> 
     <%= f.select :region_id, options_from_collection_for_select(Region.all, 'id', 'region_code'), 
:onChange => remote_function(:update => ":mobile, :telephone", :method => "get", :url => { :controller => :Settings, :action => :form_update, :id => :region_id}) %> 
    </div> 


<div class="fieldBlock"> 
<%= f.label :city_id, "City" %> 
    <%= f.select :city_id, options_from_collection_for_select(City.all, 'id', 'name'), :prompt => 'select a city' %> 
</div> 


<div class="fieldBlock"> 
<%= f.label :mobile, "Mobile" %> <%= f.text_field :mobile%></div> 

<div class="fieldBlock"> 
<%= f.label :telephone, "Telephone No" %> <%= f.text_field :telephone %></div> 

<div class="fieldBlock"> 
<% f.submit "Update Contact" %> 

At present this is the controller method that helps in prepopulating: 

def index 
setting = Setting.find_by_user_id(current_user.id) 

if setting.blank? 
    @setting = City.first.dup 

else 
    @setting = setting 
end 

我該怎麼辦以選擇區域下拉列表值的方式以ajax方式更新表單?

現在,這裏是我的form_update行動:

def form_update(id) 
setting = Setting.find_by_region_id(id) 

    respond_to do |format| 
    if setting.blank? 
     @setting = Setting.first.dup 
     format.json {@setting} 
     else 
     @setting = setting 
     format.json {@setting} 
     end 
    end 

我也不得不使用Prototype-Rails的做remote_function工作。不過我的田地都沒有得到更新,我錯過這裏..

回答

0

你需要使用選項select標籤OnChange

這應有助於[How to add an onchange event to select tag in rails]

使用:onChange選項的一個更好的解釋select_tag是這裏[http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select#51-Demo-select-onchange-invoke-an-ajax-]

編輯:

說明:當您選擇下拉菜單中的任何選項時,將執行OnChange中提供的操作。現在你可以通過ajax調用你的服務器來獲取你想要更新字段的值。要做到這一點,你需要remote_function(如下所述)。

考慮您的示例下面的片段應該工作

<%= form_for(@setting) do |f| %> 
    <div class="form"> 
     <div class="fieldBlock"> 
     <%= f.label :region%> 
     <%= f.select :region_id, options_from_collection_for_select(Region.all, 'id', 'region_code'), 
      :onchange => remote_function(... ... ...) %> 
    </div> 
<% end %> 

我在上文中僅顯示窗體的下拉部分。請注意這裏的:onchange選項。這應該包含remote_function它會像下面

:onchange => remote_function(:update => "message_id", 
          :method => "put", 
          :with => "'item=' + value", 
          :url => { :controller => :orders, :action => :set_customer_id, :id => order.id})) 

這裏:

:update:是HTML節點,其包含將被更新。因此,將所有您的:city_id,:mobile,:telephone字段放在HTML節點中,並使用您將在此處使用的唯一標識。
:method:只需按照路線中的定義使用即可。可能是GET。
:with:提供請求的一些額外屬性。
:url:您必須請求的URL。

如果這仍然無法幫助,請分享您如何嘗試。可能是一個小修復可以解決問題。

+0

請問您是否更具描述性,無論他們提到的是簡短的&沒有爲我工作 – Raul

+0

更新了一些細節。讓我知道它是否有效。 – Samiron

+0

通過控制器動作&onChange在主要問題中增加了更多細節。請看看 – Raul

相關問題