Reputation: 1424
I have an application that currently fetches data from mySQL DB. And I have a Person
table which contains columns: Name
, Gender
, Email
, Hobby
and etc.
I want to implement a "grouping-like" feature so that users can be categorized into a group by specific columns (e.g. Gender
)
What I have is something like this:
What I want to implement is to create two groups Boys/Girls by their gender and with a little +
sign so that we can expand it and see what people is in the group:
What would be the best way to do this? UPDATE: My way to implements this:
my_controller.rb:
def index
@people = Person.find_by_sql(*some sql stuff*)
@persons = @people.group_by { |t| t.gender }
end
then in view file
view.html.erb
<% @persons.sort.each do |gender, person_list| %>
<h2><%= gender %></h2>
<% for person in person_list %>
*some code here*
<% end %>
<% end %>
Upvotes: 0
Views: 276
Reputation: 89
You can uses scopes. In your Person model file, add the following:
scope :boys, where(:gender => "Male")
scope :girls, where(:gender => "Female")
Then in your controller, you can create variables for each gender group.
@boys = Person.boys
@girls = Person.girls
Finally iterate over @boys and @girls in your view.
Upvotes: 1