我希望在从下拉菜单中进行选择时更新网址。我希望查询是动态的,这里是以下代码:
<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" %>
有人能指出我正确的方向吗?
答案 0 :(得分:1)
这不是在rails中创建select的最佳方法。你应该像这样使用rails select_tag helper
:
<%= select_tag 'school_id', options_for_select(@schools.collect{ |s| [u.name, u.id] }), id: "mySchool" %>
我希望在从下拉列表中进行选择时更新网址。
我认为,只有当用户从下拉列表中选择一个值时才应显示链接,而不是显示前面的链接,因此您的代码应该是这样的:
<%= 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 }
});
});
在控制器中查找学校和用户,然后最终通过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} %>");