※コードは簡易的に書いています。
はじめに
ListテーブルとCardテーブルが一対多の関係で作成してあり、
Cardテーブルのorderカラムにはcard、作成時に指定した表示位置の順番が入っています。(1が入っていれば1番上に表示)
class Card < ApplicationRecord
belongs_to :list
end
class List < ApplicationRecord
has_many :cards, dependent: :destroy
end
やりたいこと
表示順をorderカラムの数値順にしたいので、list.cardsを取得したときには、orderカラムで希望した順に取得しておきたい。
<% @lists.each do |list| %>
<% list.cards.each do |card| %>
<%= card.title %>
<% end %>
<% end %>
つまずいたところ
様々なサイトで調べていく中で、以下のようにhas_many
に対してスコープを指定すればいいということが分かった。
class List < ApplicationRecord
has_many :cards, -> { order('カラム名 ASC') }, dependent: :destroy
end
しかし、Cardテーブルの他のカラムでは、思うように並び替えができているのに、orderカラム
のみエラーが発生していた。
ActionView::Template::Error (SQLite3::SQLException: near "order": syntax error):
原因
SQLの予約語と呼ばれるものをカラム名に使用していた事が原因だった。
解決策
ダブルクォート("")で括むことで、並び替えて取得するようになった。
class List < ApplicationRecord
has_many :cards, -> { order('"order" ASC') }, dependent: :destroy
end
参考サイト
rails アソシエーション先の並べ替えを維持したい
[ Oracle ] テーブル名やカラム名にSQL予約語を使用する
SQL の一般的な予約語