Railsでチャットができるアプリを制作しています。
投稿毎に関連付けられたユーザーの画像を表示させたいのですが、うまくいかなく困っております。
Roomコントローラーのshowアクションで、chatコントローラーの投稿を表示させています。
chatを作成したユーザーのユーザー画像を取得する方法がわからない点が問題だと考えています。
使用Gem
- devise
- paperclip
Model
user.rb
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :rooms has_many :chats, dependent: :destroy has_attached_file :avatar, styles: { medium: "300x300>", thumb: "25x25>" } validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/ end
room.rb
class Room < ActiveRecord::Base belongs_to :user has_many :chats, dependent: :destroy has_many :tasks has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" } validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ end
chat.rb
class Chat < ActiveRecord::Base belongs_to :room belongs_to :user end
Controller
chats_controller.rb
class ChatsController < ApplicationController before_action :set_room before_action :set_chat, except: [:create] def new c_params = chat_params c_params[:user_id] = current_user.id @chat = @room.chats.create end def create c_params = chat_params c_params[:user_id] = current_user.id @chat = @room.chats.create(c_params) if @chat.save redirect_to @room else render "new" end end def update if @chat.update(chat_params) redirect_to @room else render "edit" end end def destroy @chat.destroy redirect_to room_path(@room) end private def chat_params params[:chat].permit(:comment, :user_id) end def set_room @room = Room.find(params[:room_id]) end def set_chat @chat = @room.chats.find(params[:id]) end def room_params @room = Room.find(params[:room_id]) end end
rooms_controller.rb
class RoomsController < ApplicationController before_action :find_room, only: [:show, :edit, :update, :destroy] def index @rooms = Room.all.order("created_at DESC") end def show @chats = @room.chats.all.order("created_at DESC") @tasks = @room.tasks.all.order("created_at DESC") end def new @room = current_user.rooms.build end def create @room = current_user.rooms.build(room_params) if @room.save redirect_to @room else render "new" end end def edit end def update if @room.update(room_params) redirect_to @room else render "edit" end end def destroy @room.destroy redirect_to root_path end private def room_params params.require(:room).permit(:title, :description, :image) end def find_room @room = Room.find(params[:id]) end end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/09 17:46