Rails Ruby Simple_form 按州筛选城市

Filter cities by state in Simple_form Ruby on Rails

我正在使用 simple_form 在当前项目中创建脚手架表单。我需要一些帮助来改进我的地址 CRUD。在我db:seed之后有很多城市注册了。

我目前的地址表是:

<%= simple_form_for @address, :html => { :class => 'form-horizontal' } do   |f| %>
<%= f.input :street%>
<%= error_span(@address[:street]) %>
<%= f.input :zip%>
<%= error_span(@address[:zip]) %>
<%= f.label :city_id %>
<%= f.collection_select(:city_id , City.all, :id, :name, prompt: true) %>
<%= error_span(@address[:city_id]) %>

<%= f.button :submit, :class => 'btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
            address_path, :class => 'btn btn-default' %>
<% end %>

如何过滤我的城市 collection 首先选择州?

 <%= f.collection_select(:city_id, City.all, :id, :name, prompt: true) %>

谢谢

将此 class 方法添加到您的模型中:

def self.by_state
  order('state DESC')
end

然后在您的表单中使用它:

<%= f.collection_select(:city_id , City.by_state, :id, :name, prompt: true) %>