閲覧ありがとうございます
Railsフレームワークを使ってアプリ製作中なのですが、DBの結合で詰まってしまったので質問させてください。
#質問
sourcesテーブルとsentencesテーブルを結合したいと思い、joinsを使ってみましたが、sourceのカラムしか変数に代入されていないようです。どのようにすれば、うまく結合できるのでしょうか。
#コード
[rails console上]
a = Source.joins(:sentence).where(id:1)
[結果]
Source Load (1.2ms) SELECT `sources`.* FROM `sources` INNER JOIN `sentences` ON `sentences`.`source_id` = `sources`.`id` WHERE `sources`.`id` = 1 LIMIT 11 => #<ActiveRecord::Relation [#<Source id: 1, type_id: 1, main_title: "piyopiyop", author: "gehog">]>
[models/sentence.rb]
class Sentence < ApplicationRecord belongs_to :source end
[models/source.rb]
class Source < ApplicationRecord has_one :sentence end
#データベース
[sentences table]
+----+---------+-----------+---------------+ | id | user_id | source_id | sentence | +----+---------+-----------+---------------+ | 1 | 1 | 1 | hogehogehoge | | 2 | 2 | 2 | 2hogehogehoge | +----+---------+-----------+---------------+
[sources table]
+----+---------+------------+--------+ | id | type_id | main_title | author | +----+---------+------------+--------+ | 1 | 1 | piyopiyop | gehog | | 2 | 2 | piyopiyopi | gehoge | +----+---------+------------+--------+
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/25 04:23
2018/12/26 14:31
2018/12/27 13:47