How to output information grouped by each value in rails?

Asked 2 years ago, Updated 2 years ago, 36 views

I'm a beginner at rails.
I'm studying at rails5.

Prefectures, stations, and route names are all different models, and we have associations.

########Model####################################
# pref.rb (province)
class Pref<ApplicationRecord
  has_many —Stations
end

# station.rb (station name)
class Station <ApplicationRecord
  belongs_to —pref
  belongs_to:line, foreign_key: 'line_id', primary_key: 'line_id'
end

# line.rb (route name)
class Line <ApplicationRecord
  has_many:stations, class_name: 'Station', foreign_key: 'line_id', primary_key: 'line_id'
end


######### Controller ########
#stations_controller.rb
class StationsController <ApplicationController
  def index
    @pref_name =Station.find_by (pref_id:params[:area_id])
    @stations=Station.where(pref_id:params[:area_id])
  end

  def show
  end

end


#########View ########
#stations/index.html.erb

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h1><%=@pref_name.pref.name%>|<%[email protected]%>Station|Stations #index</h1>
      <p>Find me in app/views/stations/index.html.erb</p>

          <%@stations.each do | station | %>
            <div class="panel panel-default">
                  <div class="panel-heading">%=station.line.line_name%>/div>
                <ul class="list-group">
                      <lic class="list-group-item">%=station.station_name%>/li>
                </ul>
            </div>
          <%end%>
    </div>
  </div>
</div>

DB is mysql and
prefs table
id:integer
pref_cd:integer
name:string

stations table
id:integer
pref_id:integer
station_cd:integer
station_name:string
line_id:integer

lines table
id:integer
line_id:integer
line_name:string

Currently, the display is as follows.

Enter a description of the image here

[Yamanote Line]

Ozaki [Yamanote Line]
Gotanda Corporation [Yamanote Line]
Meguro
What you see above…

[Yamanote Line]

Ozaki Gotanda Corporation Meguro
When all the stations on the Yamanote Line are printed out...
[Nambu Line]
Yano-guchi Corporation Inagi Naganuma Corporation Nantama

Grouping on the line like that?I would like to print it out.
I'm thinking about grouping the line_id (track ID) of each station and somehow turning it around with each, but I can't get an answer.
What should I do to solve this problem?
Please teach me!!!

ruby-on-rails ruby

2022-09-30 19:33

1 Answers

group_by to do this

@[email protected]_by {|s|s.line.line_name}

You can get the following hash

{"Yamanote Line"=>[Arrangement of stations on the Yamanote Line], "Nambu Line"=>[Arrangement of stations on the Nambu Line]}

After that, you can loop this hash in a good way.


2022-09-30 19:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.