我已经开发了可能的国家/地区选择下拉列表,并且我想将此行为分解到地址模型中,这样我就不必每次都复制动态行为(或多或少在视图和控制器之间拆分)我希望用户能够输入完整的地址。
基本上,我正试图让我的脚趾更深入 DRY。但我不确定在哪里嵌入这些行为。我是使用模型还是助手来构建必要的表单?最重要的是:我在哪里以及如何调用动态行为来更新状态列表?我需要一个地址控制器,还是可以在模型中完成?
换句话说,我现在在视图中看到的是:
# _refine.html.erb
<tr>
<td>
<%= label_tag :dest_country, 'Country: ' %></td><td>
<%= select_tag :dest_country,
options_for_select(Carmen::country_names
<< 'Select a country',
:selected => 'Select a country'),
{:include_blank => true,
:id => 'country_select',
:style => 'width: 180px',
:onchange => remote_function(
:url => {:action => 'update_state_select'},
:with => "'country='+value")} %>
</td>
</tr>
<tr>
<div id="state_select_div">
<td><%= label_tag :dest_state, 'State:   ' %></td>
<td><%= select_tag :dest_state,
options_for_select(Carmen::states('US').collect{
|s| [s[0],s[0]]} << ['Select a state'],
:selected => 'Select a state'),
{:style => 'width: 180px'} %></td>
</div>
</tr>
更新方法在控制器中:
# search_controller.rb
def update_state_select
# puts "Attempting to update states"
states = []
q = Carmen::states(Carmen::country_code(params[:country]))
states = q unless q.nil?
render :update do |page|
page.replace_html("state_select_div",
:partial => "state_select",
:locals => {:states => states }
)
end
end
最后,我得到了一个带有正确名称或空白文本字段的部分:
# _state_select.html.erb
<% unless states.empty? or states.nil? %>
<%= label_tag :dest_state, 'Select a state' %>
<br/> <%= select_tag :dest_state,
options_for_select(states.collect{|s| [s[0],s[0]]}
<< ['Select a state'],
:selected => 'Select a state'),
{:style => 'width: 180px'} %>
<% else %>
<%= label_tag :dest_state, 'Please enter state/province' %><br />
<%= text_field_tag :dest_state %>
<% end %>
现在,我想做的是能够通过模型关联地址(例如,Person has_one :address)并在创建新人的表单中,能够使用类似的东西
<%= label_tag :name, 'What's your name?' %>
<%= text_field_tag :name %>
<%= label_tag :address, 'Where do you live?' %>
<%= address_fields_tag :address %>
这可以生成适当的下拉列表,动态耦合在一起,其结果可以通过 Person.address.country 和 Person.address.state 访问。
提前致谢!