如何在rails中搜索属性的嵌套值

时间:2015-07-26 08:26:32

标签: ruby-on-rails activerecord attributes

您好我有一个示例应用,它在种子文件中有3个对象:

students =[{
  name: "John",
  hobby: "sport"},
{
  name: "Bill",
  hobby: "science"},
{
  name: "Evit Tom",
  hobby: ["sport","science"]}]

students.each do |student|
  School.create(student)
end

我用复选框形式搜索它们:

<%= form_tag student_list_path %>
  Hobby:
  <ul>
    <li><%= check_box_tag 'hobby[]', "Sport" %> Sport</li> 
    <li><%= check_box_tag 'hobby[]', "Science" %> Science</li>     
  </ul>            
<%= submit_tag "Show" %>

在控制器中我有:

@hobby = params[:hobby]
@schools = Student.student_search(@hobby).to_a

在我的学生模型中:

     def self.student_search(hobby)
       School.where(hobby: hobby)
     end

我的麻烦是得到邪恶的汤姆对象。我知道这是因为这个对象的hobby属性的数组值。但我不知道怎么做到这一点。

我试图在我的Studen模型中制作一个'search_array'方法。

   def array_search(array)
     temp = []
     array.each do |value|
       case value
       when Array
         array_search(value)
       else
         temp << value
       end
       temp
     end
   end

并在以下搜索操作中使用它:

     def self.student_search(hobby)
       hobby_s = array_search(hobby)
       School.where(hobby: hobby_s)
     end

但是我得到了未定义的方法,我不知道为什么因为它是在Student类中定义的。

我的主要问题是如果你有任何想法请求获取'邪恶汤姆'对象:)我将获得自己的代码。我只需要提示。

0 个答案:

没有答案