0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

カラム名にSQLで使われる単語を設定した時のorderの仕方

Posted at

※コードは簡易的に書いています。

はじめに

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 の一般的な予約語

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?