###前提・実現したいこと
rails4 ローカル環境
現在メッセージ機能を実装してラインのようなメッセージのやりとりができるようにしたいと思っています。
機能自体は実装できたのですが、会話一覧ページ(誰とメッセージのやり取りをしているか表示するラインのトーク一覧のようなページ)で最新のメッセージを一件取得する方法が分かりません。
conversations : 会話情報を格納するテーブル
messages : 会話の個々のメッセージを格納するテーブル
として実装しました。
###該当のソースコード
conversations/index.html.erb
ここで最新のメッセージを一件だけ取得したい
<div class="container message"> <div class="wrapper col-md-8 col-md-offset-2 col-sm-10 message-index"> <h2>メッセージ一覧</h2> <% @conversations.each do |conversation| %> <div class="row conversation-list"> <% if conversation.target_user(current_user).present? %> <%= link_to conversation.target_user(current_user).name, conversation_messages_path(conversation)%> <% end %> </div> <% end %> </div> </div>
messages_controller.rb
messages_controller.rb
messageモデル
class Message < ActiveRecord::Base belongs_to :conversation belongs_to :user validates_presence_of :body, :conversation_id, :user_id def message_time created_at.strftime("%m/%d/%y at %l:%M %p") end end
conversations_controller.rb
class ConversationsController < ApplicationController before_action :authenticate_user! def index @users = User.all @conversations = Conversation.all end def create if Conversation.between(params[:sender_id], params[:recipient_id]).present? @conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first else @conversation = Conversation.create!(conversation_params) end redirect_to conversation_messages_path(@conversation) end private def conversation_params params.permit(:sender_id, :recipient_id) end end
Conversationモデル
class Conversation < ActiveRecord::Base belongs_to :sender, foreign_key: :sender_id, class_name: 'User' belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User' has_many :messages, dependent: :destroy validates_uniqueness_of :sender_id, scope: :recipient_id scope :between, -> (sender_id,recipient_id) do where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id) end def target_user(current_user) if sender_id == current_user.id User.find(recipient_id) elsif recipient_id == current_user.id User.find(sender_id) end end end
データベーステーブル
create_table "messages", force: :cascade do |t| t.text "body" t.integer "conversation_id" t.integer "user_id" t.boolean "read", default: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "messages", ["conversation_id"], name: "index_messages_on_conversation_id", using: :btree add_index "messages", ["user_id"], name: "index_messages_on_user_id", using: :btree create_table "conversations", force: :cascade do |t| t.integer "sender_id" t.integer "recipient_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
どのように最新のメッセージを一件取得するばいいかアドバイス頂けると嬉しいです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/03/29 05:56
退会済みユーザー
2017/03/29 06:31
2017/03/29 06:44 編集
2017/03/29 08:44