まずはモデルで関連付けを行います。
dependent: :destroy
はbuildingが削除されたらroomも削除するといったメソッドです。
scopeメソッドを使うとコントローラで呼び出すだけで並び替えができるようになります。
model/building.rb
class Building < ApplicationRecord
has_many :rooms, dependent: :destroy
scope :latest, -> {order(created_at: :desc)}
scope :old, -> {order(created_at: :asc)}
scope :short, -> {order(station_minute: :asc)}
scope :long, -> {order(station_minute: :desc)}
model/room.rb
class Room < ApplicationRecord
belongs_to :building
viewでパラメーターをparams[:keyword]
として送信します。
参考:https://qiita.com/kurawo___D/items/7604f709a9ec28808540
buildings/index.html.haml
%dl
%dt 並び替え
%dd
= form_with model: @building, url: @building, method: :get, local: true do |form|
= form.select :keyword, [ ['新しい順', 'latest'],
['古い順', 'old'],
['賃料が高い順', 'high'],
['賃料が低い順', 'low'],
['駅が近い順', 'short'],
['駅が遠い順', 'long'],
]
= form.submit 'save'
コントローラーではこのように記述してあげるとviewのプルダウンで選択された値とマッチした並び替えが行われます。
includesメソッド
を使ってbuildingとroomsのテーブルをつなげてあげることによりbuilding_controllerでroomsの並び替えを行うことができます。
includesメソッドについて
buildingはscopeを使用しているのでコントローラーではorderを宣言しなくても並び替えが行われます。
roomsはscopeを使用していないのでorderメソッドを使用しています。
controllers/buildings_controller.rb
def index
if 'latest' == params[:keyword]
Building.all.includes(:rooms).latest
elsif 'old' == params[:keyword]
Building.all.includes(:rooms).old
elsif 'short' == params[:keyword]
Building.all.includes(:rooms).short
elsif 'long' == params[:keyword]
Building.all.includes(:rooms).long
elsif 'high' == params[:keyword]
Building.all.includes(:rooms).order("rooms.rent desc")
elsif 'low' == params[:keyword]
Building.all.includes(:rooms).order("rooms.rent")
else
Building.all.includes(:rooms).latest
end
@buildings = @q.result(distinct: true).page(params[:page]).per(10)
end
以上のやり方でアソシエーションをしたカラムの並び替えができると思います。
参考になれば幸いです。