【问题标题】:Updating URL query string with JS / Rails and a dropdown form使用 JS/Rails 和下拉表单更新 URL 查询字符串
【发布时间】:2014-12-24 03:11:38
【问题描述】:

我希望在从下拉列表中进行选择时更新 url。我希望查询是动态的,这里是以下代码:

  <select id="mySchool" onchange="this.form.submit()">
    <% @schools.each do |school| %>
      <option value="<%= school.id %>"><%= school.name %></option>
    <% end %>
  </select>

  <%= link_to "Apply School", "schools/assign_users?user_id=#{@user.id}&school_id=", :class => "btn btn-primary", :type => "button" %>

谁能指出我正确的方向?

【问题讨论】:

    标签: javascript html ruby-on-rails ajax forms


    【解决方案1】:

    这不是在 Rails 中创建选择的最佳方式。你应该像这样使用rails select_tag helper

    <%= select_tag 'school_id', options_for_select(@schools.collect{ |s| [u.name, u.id] }), id: "mySchool" %>
    

    我希望在从下拉列表中进行选择时更新 url。

    我认为,与其预先显示链接,不如仅在用户从下拉列表中选择值时才显示链接,因此您的代码应该是这样的:

    <%= select_tag 'school_id', options_for_select(@schools.collect{ |s| [u.name, u.id] }), id: "mySchool" %>
    
    <div id="schoolLink"></div>
    
    #_link.html.erb
    <%= link_to "Apply School", "schools/assign_users?user_id=#{user.id}&school_id=#{school.id}", :class => "btn btn-primary", :type => "button" %>
    

    现在创建一个您想要将 ajax 请求发送到的路由:

    post 'selected_school/:id' => 'school#selected', as: "select_school"
    

    编写一个 js 函数,该函数将在更改下拉列表中的值时发送 ajax 请求

    $(document).on("change","#mySchool",function(e){
      var school_id = $(this).val();
      $.ajax({
        type: "POST",
        url: "/selected_school",
        data: {id : school_id }
      });
    });
    

    在controller里面找到学校和用户,最后通过js渲染链接

    #school_controller.rb
    def selected
      @school = School.find(params[:id]) # find school by the passed id
      @user = current_user # your logic to find user
    end
    
    #app/views/school/selected.js
    $("#schoolLink").html("<%=j render partial: 'link', locals: {user: @user, school: @school} %>");
    

    详情请查看Working with Javascript in Rails

    【讨论】:

      猜你喜欢
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多