現在 ruby on rails でコードを書いています。
二つのモデルを紐づけるのに多対多の方式でコードをかくと効率的とのことで、roomおよびuserモデルを紐付けることにしました。
実現したいこととしましては、サイト観覧中のユーザーをサイトに表示することです。
現時点で、モデルの紐付けは完了したのですが、関連助けられたデータの呼び出し方がうまく理解できていないです。
room_controller.rbにおいてshowアクションのところでroomに紐付けられたuserの名前をshow.html.erbに表示したいです。
色々なサイトを見て、以下のように試行錯誤したのですがうまく行きません。どのようにし、どのように理解するのが正しいのでしょうか。
room_controller.rb
1 def show 2 if logged_in? 3 @room = Room.find(params[:id]) 4 @rooms = Room.all 5 @user = User.find(current_user.id) 6 @users = @room.room_groups.create(user:@user) 7 @u = @room.room_groups 8 @h = @room.users.ids 9 #@users = Room.room_groups.where() 10 @messages = @room.messages 11 end 12 end
データベースは以下のように保存されています。
sqlite> select * from room_groups; 1|1|1|2018-11-22 21:46:21.646205|2018-11-22 21:46:21.646205 2|2|1|2018-11-22 21:46:33.270255|2018-11-22 21:46:33.270255 3|1|1|2018-11-22 21:46:50.887471|2018-11-22 21:46:50.887471 4|1|1|2018-11-22 21:48:24.367521|2018-11-22 21:48:24.367521 5|1|1|2018-11-22 21:49:52.361598|2018-11-22 21:49:52.361598 6|1|1|2018-11-22 21:50:10.778949|2018-11-22 21:50:10.778949
作成したモデルの各テーブルのカラムは以下のschema通りです。
schema
1 2 3 create_table "rooms", force: :cascade do |t| 4 t.string "title" 5 t.datetime "created_at", null: false 6 t.datetime "updated_at", null: false 7 end 8 9 create_table "users", force: :cascade do |t| 10 t.string "name" 11 t.string "email" 12 t.datetime "created_at", null: false 13 t.datetime "updated_at", null: false 14 t.index ["email"], name: "index_users_on_email", unique: true 15 end 16 17create_table "room_groups", force: :cascade do |t| 18 t.integer "user_id" 19 t.integer "room_id" 20 t.datetime "created_at", null: false 21 t.datetime "updated_at", null: false 22 t.index ["room_id"], name: "index_room_groups_on_room_id" 23 t.index ["user_id"], name: "index_room_groups_on_user_id" 24 end
モデルファイルは以下の通りです。
class RoomGroup < ApplicationRecord belongs_to :user belongs_to :room end
class Room < ApplicationRecord has_many :room_groups has_many :users ,through: :room_groups end
class User < ApplicationRecord has_many :room_groups has_many :rooms ,through: :room_groups end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/23 01:44
退会済みユーザー
2018/11/23 10:26
2019/02/15 09:59