我按照此railscast成功地将国家和城市显示为动态选择菜单,以便在添加新个人资料时选择国家/地区和城市。我在app / views / search中创建了一个带有索引操作和视图“ index.html.erb ”的控制器“ search_controller.rb ”。现在我想在app / views / search / index.html.erb中创建一个具有
的搜索表单应用/模型/ profile.rb
has_many :categorizations
has_many :subjects, through: :categorizations
belongs_to :country
belongs_to :city
应用/模型/ subject.rb中
has_many :categorizations
has_many :profiles, through: :categorizations
应用/模型/ categorization.rb
belongs_to :profile
belongs_to :subject
应用/模型/ country.rb
has_many :cities
has_many :profiles
应用/模型/ city.rb
belongs_to :country
has_many :profiles
应用/视图/简档/ _form.html.erb
<div class="field">
<%= f.label :country_id %><br />
<%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %>
</div>
应用/资产/ Javascript角/ profiles.js.coffee
$('#profile_city_id').parent().hide()
cities = $('#profile_city_id').html()
$('#profile_country_id').change ->
country = $('#profile_country_id :selected').text()
escaped_country = country.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options = $(cities).filter("optgroup[label='#{escaped_country}']").html()
if options
$('#profile_city_id').html(options)
$('#profile_city_id').parent().show()
else
$('#profile_city_id').empty()
$('#profile_city_id').parent().hide()
答案 0 :(得分:0)
以下是我的解决方案sunspot-solr
用于搜索,twitter-typeahead-rails
用于自动完成。在模型中添加可搜索的块后,我使用以下代码为我的应用程序。我通过twitter typeahead将我的主题列表加载到本地存储中,因为它不会改变,但如果需要,你可以使用json。
应用/控制器/ search_controller.rb 强>
def index
@search = Profile.search do
fulltext params[:search]
with(:city_id, params[:city]) if params[:city].present?
end
@profiles = @search.results
end
应用/视图/搜索/ index.html.erb 强>
<%= text_field_tag :search, params[:search], :class => 'typeahead' %>
<div class="field">
<%= select_tag :country, options_from_collection_for_select(Country.all, :id, :name, params[:country]), include_blank: true %>
</div>
<div class="field">
<%= select_tag :city, option_groups_from_collection_for_select(Country.order(:name), :cities, :name, :id, :name, params[:city]), include_blank: true %>
</div>
<%= submit_tag "search", :name => nil, :class => 'btn btn-default' %>
应用/资产/ Javascript角/ profiles.js.coffee 强>
$('#city').parent().hide()
cities = $('#city').html()
$('#country').change ->
country = $('#country :selected').text()
escaped_country = country.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options = $(cities).filter("optgroup[label='#{escaped_country}']").html()
if options
$('#city').html(options)
$('#city').parent().show()
else
$('#city').empty()
$('#city').parent().hide()
$('.typeahead').typeahead({
local: ["3D Design", "Architecture", "Chemical engineering", ...]
limit: 10
});