如何从选择标记栏中搜索数据

时间:2018-06-15 11:20:28

标签: ruby-on-rails ruby

image我正在尝试使用rails开发一个Web应用程序,它包含课程类别和位置模块。课程类别位置与'has_many'的关系。

在我的课程表格中,我需要根据类别整理课程。任何人都可以帮我解决这个问题吗?

course.html.erb:

 <%= select_tag(:category_id, options_for_select(Category.pluck(:name, :id)),  class: "form-control custom-select" )%> 

3 个答案:

答案 0 :(得分:0)

您可以使用options_from_collection_for_select方法来避免使用pluck。如果我没有弄错,你想按名字对类别进行排序。所以:

<%= select_tag :category_id,
               options_from_collection_for_select(Category.order(:name), :id, :name),
               class: "form-control custom-select" %>

<强>更新

所以看起来你需要在下拉列表更改时发送AJAX请求并重新填充表格内容。请查看这些文章:

我们不知道您使用什么来生成表格(简单部分,DataTable-plugin或其他内容),因此我们无法向您建议针对您的案例的最佳解决方案。但是,例如,您可以将更新的表内容作为AJAX响应获取,并以HTML格式重新填充表格。

答案 1 :(得分:0)

如果我理解正确,您希望将您获得的课程列表排序为搜索结果。

所以,试试这个:

@courses = Course.joins(:categories, :locations).where("categories.id LIKE ? and locations.id LIKE ?", "%#{params[:category_id]}%", "%#{params[:location_id]}%").order("categories.name ASC")

答案 2 :(得分:0)

通过添加以下代码解决: course_controller.rb

def index
  @courses = @courses.where(category_id: params[:category_id]) if params[:category_id].present?
end

课程index.html.erb

<%= form_tag courses_path, :method => 'get' do %>
   <%= select_tag(:category_id, options_for_select(Category.order(:name).pluck(:name, :id) ,:selected =>params[:option]), onchange: 'this.form.submit();', class: "form-control custom-select" , include_blank: true  )%>
 <% end %>
相关问题