回复做格式问题

时间:2014-03-28 08:30:01

标签: ruby-on-rails ruby ajax ruby-on-rails-4

我有2个像State和Cities这样的字段。城市将受到相应国家的影响。我的领域不是纯粹的DropDown。它们就像一个带有自动完成功能的输入字段,它允许我们选择多个选项(参考图像..)

screenshot1

screenshot2

这就是我加载状态的方式。

<%= jl.select :state_id,  State.all.map{|j| [j[:name], j[:id]]}, {}, {class: 'select2', multiple: true, 'data-placeholder' => 'Type State to Search'} %>

为了加载城市,我编写了jquery,它发送了一个ajax请求,然后将响应附加到其成功函数中。

我的控制器就像

def update_city_select
    @states = State.where(name: params[:name]).order(:id) unless params[:name].blank?    
    @cities = City.where(state_id: @states.first.id).order(:name) unless @states.first.id.blank?
    respond_to do |format|
      format.html { render layout: false }
      format.js
      format.xml
    end
  end

我的update_city_select.html.erb就像

<%= select_tag 'city_id', options_from_collection_for_select(@cities, "id", "name", @states), {}, {class: 'select2', multiple: true, 'data-placeholder' => 'Type City to Search'} %>

事情是我的终端总是收到错误..

(wrong number of arguments (4 for 1..3)):
    1: <%= select_tag 'city_id', options_from_collection_for_select(@cities, "id", "name", @states), {}, {class: 'select2', multiple: true, 'data-placeholder' => 'Type State to Search'} %>

如果我删除{}表格update_city_html页面,它会正常工作。但我得到的只是一个简单的下拉列表,在我的第一张图片中没有像阿拉巴马加利福尼亚那样的输入字段。 有什么方法可以解决这个问题。

2 个答案:

答案 0 :(得分:1)

我认为您的问题与您如何呈现表单有关,而不是Rails中的respond_to阻止。我看到您正在使用select2


select_tag

我相信你的select_tag没有被正确调用。这与您是否从content-type

调用右respond_to无关

这看似显而易见,但事实上你是在独立于你的表格调用select_tag,因此这将是问题的原因


<强> options_from_collection_for_select

诚然,我没有select2的任何经验,但我一直在寻找,我认为你的问题可能与你的{{ 3}},以及您的{}

<%= select_tag 'city_id', options_from_collection_for_select(@cities, "id", "name", @states), {}, {class: 'select2', multiple: true, 'data-placeholder' => 'Type State to Search'} %>

我会测试只将id传递给options_from_collection_for_select的最后一个参数(看看你发送的整个对象是否会成为Rails的问题)


选择

正如options_from_collection_for_select所述,您调用select_tag基本上意味着您只需Paul the octopus即可,而have 3 arguments则有4:

select_tag(name, option_tags = nil, options = {})

select(object, method, choices, options = {}, html_options = {})

表面级修补程序将使用form_builder新对象添加select标记,而不是裸select_tag

#update_city_select.html.erb 
<%= form_for @instace_var_for_form do |jl| %>
    <%= jl.select :city,  options_from_collection_for_select(@cities, "id", "name", @states), {}, {class: 'select2', multiple: true, 'data-placeholder' => 'Type State to Search'} %>
<% end %>

#ajax
$(document).on("ajax:success", "select", function(data) {
    //pull select form form
    $("element").append(select);
});

答案 1 :(得分:0)

select_tag只接受3个参数。看看它的definition。 所以把它保留为

`select_tag 'city_id', options_from_collection_for_select(@cities, "id", "name", @states), {class: 'select2', multiple: true, 'data-placeholder' => 'Type City to Search'}`

请务必为您的ajax请求设置正确的格式(这应该是 jsonp

$("#your_states_input_id").select2({
  placeholder: "Search for a city",
  ajax: { 
    url: "your_city_url_here",
    dataType: 'jsonp'
  }
});   

有关详细信息,请查看select2 ajax example