Rails 初心者です。
Excelのvlookup関数のように、他テーブルのカラムからデータを引っ張ってくる方法を探しています。
具体的には、以下のようなことをするのが目的です。
1). モデル(テーブル)が以下のように4つあります。
ruby
1class User < ApplicationRecord 2 has_many :user_shop_items 3 has_many :user_shop_item_categories 4 has_many :shop_items, through: :user_shop_items 5 has_many :shop_item_categories, through: :user_shop_item_categories 6end 7 8class ShopItem < ApplicationRecord 9 has_many :user_shop_items 10 has_many :users, through: :user_shop_items 11end 12 13class UserShopItem < ApplicationRecord 14 belongs_to :user 15 belongs_to :shop_item 16end 17 18class UserShopItemCategory < ApplicationRecord 19 belongs_to :user 20 belongs_to :shop_item_category 21end
User
id | name | |
---|---|---|
1 | A | |
2 | B | |
3 | C |
ShopItem
id | name | shop_item_category_id |
---|---|---|
1 | A' | 1 |
2 | B' | 2 |
3 | C' | 2 |
4 | D' | 3 |
UserShopItem
|id|user_id|user_sub_id|shop_item_id|
|:--|:--:|--:|
|1|1|1|1|
|2|1|2|2|
|3|2|1|3|
|4|1|3|4|
UserShopItemCategory
|id|user_id|shop_item_category_id|priority|
|:--|:--:|--:|
|1|1|1|1|
|2|1|2|2|
|3|2|2|1|
|4|1|3|3|
2). UserShopItemテーブルにおいて、shop_item_idをもとにShopItemテーブルからshop_item_category_idを引っ張ってくる。
さらにそのshop_item_category_idとuser_idをもとに、UserShopItemCategoryテーブルからpriorityを引っ張ってくる。
最後に、shop_item_idをもとに、ShopItemテーブルからshop_item_nameを引っ張ってくる。
すると、UserShopItemテーブルに3カラム加わり、以下のようになる。
UserShopItem
|id|user_id|user_sub_id|shop_item_id|shop_item_category_id|priority|shop_item_name|
|:--|:--:|--:|
|1|1|1|1|1|1|A'|
|2|1|2|2|2|2|B'|
|3|2|1|3|2|1|C'|
|4|1|3|4|3|3|D'|
このテーブルから、user_idが1のshop_item_nameを取り出し、priority順に表示する。つまり、以下のように表示される。
A'
B'
D'
以上が私のやりたいことです。
UserShopItemとUserShopItemCategoryのテーブルをwhereメソッドで繋ごうとしているのですが、そもそもの構築方法がよくわからずに苦戦しています。
質問が若干抽象的になってしまい、申し訳ございません。
さらに進展したらコードも追記いたしますが、構築方法のヒントだけでも教えていただけると大変助かります。
どうぞよろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー