Ruby on Rails的动态下拉列表(select_tag)

时间:2014-05-09 22:01:52

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

我一直在尝试创建3个动态下拉列表,第一个更改了sencond的内容,第二个更改了thrid的内容。

我没有找到这样做的例子,我找到了一个例子,你将所有信息发送到客户端并在那里进行过滤,但这不是我想要的。 我希望每次选择更改时都与服务器进行交互。

如果有人有教程或可以举一个简短的例子,我真的很感激

由于

1 个答案:

答案 0 :(得分:3)

你需要3件事才能发挥作用:

1 - 您选择的更改活动的Javascript:

// This will monitor your select control and start the process after its content has changed
$('select#my_select_control').change( select_has_changed(this) );

2 - Javascript Ajax控制器功能:

// This will send the selected value to your Rails server
function select_has_changed(obj)
{
  // We get the selected value
  var value = $(obj).val();

  // It's a good idea here to verify the value.
  // For example if the value is empty we can empty the content 
  //   of the target select control and do not go through ajax

  // We make the ajax call to the rails controller
  $.ajax({url: '/path/to/controller/action', 
          data: {value: value},
          // We are requesting for json response, but you can use html if you like
          dataType: "json",
          // Get method, or other is you like, you just have to 
          //   define it accordingly in your routes
          method: 'get'
          // This is the function to call when ajax succeed
          success: function (data) { fill_up_form(data, obj) }
  });
}

// This is called when Ajax was successful , and it will 
//   fill up your target select control
function fill_up_form(data, obj)
{
  content = ... // Here you loop through your json data to create
                //   a set of OPTION tags
                // Or if you used html as dataType, the rails server had it done
                //   so you can inject directly in your select target control
  $('select#my_target_control').html(content);
}

3 - Rails控制器方法

# The action method that receive the ajax call
#   you must have set-up your routes accordingly 
def get_my_ajax_data
  # This fetches the data from the database
  # Note that we are using `params` with the same index as 
  #   we used in the `data` hash of the ajax call
  #   which, in my example is `value`
  records = Model.where(field: params[:value])

  # For a json request we return a collection of [id, text]
  #   that can be used to populate your target select control
  # As an alternative we could have render a template if
  #   we was requesting for html content
  render json: records.collect{ |r| {id: r.id, text: r.name} }
end