【发布时间】:2009-06-22 15:22:20
【问题描述】:
我已经开发了可能的国家/地区选择下拉菜单,我想将此行为分解到地址模型中,这样我就不必复制每个动态行为(视图和控制器之间或多或少的拆分)并且每次我希望用户能够输入完整的地址。
基本上,我正在尝试将我的脚趾深入到 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 访问。
提前致谢!
【问题讨论】:
-
您能说得更具体一点,或许可以举一些当前界面与所需界面的例子吗?
标签: ruby-on-rails ruby model-view-controller refactoring dry