问题
Hi I have a sample app which has 3 objects in seed file:
students =[{
name: "John",
hobby: "sport"},
{
name: "Bill",
hobby: "science"},
{
name: "Evit Tom",
hobby: ["sport","science"]}]
students.each do |student|
School.create(student)
end
I search them with check boxes form:
<%= 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" %>
And in controller I have:
@hobby = params[:hobby]
@schools = Student.student_search(@hobby).to_a
And in my Student model:
def self.student_search(hobby)
School.where(hobby: hobby)
end
My trouble is to get the Evil Tom object. I know that this is becouse of the array value of this object hobby attribute. But I don`t know how to get to it.
I tried to make a 'search_array' method in my Studen model.
def array_search(array)
temp = []
array.each do |value|
case value
when Array
array_search(value)
else
temp << value
end
temp
end
end
And use it in a search action like this:
def self.student_search(hobby)
hobby_s = array_search(hobby)
School.where(hobby: hobby_s)
end
But I get undefinded method, I don`t know why since it is defined in Student class.
My main problem is how to get the 'Evil Tom' object if you have any ideas pleas post :) I will get code by my self. I need just the hint.
来源:https://stackoverflow.com/questions/31635016/how-to-search-through-nested-values-of-attributes-in-rails