LoginSignup
1
0

More than 1 year has passed since last update.

【rails】DM機能からグループチャット作ってみた〜

Posted at

前提

この記事でDM機能を作っときましょう

やり方ー

Controller

rooms_controller.rb
(略)
    def new
        @users = User.all
        @current_room = Room.find(params[:id])
        @entry = Entry.new
    end
    def room_add_user
        entry = Entry.new(entry_params)
        if entry.save
            redirect_to room_path(entry.room_id)
        else
            redirect_to new_room_path(entry.room_id)
        end
    end
(略)
    private
    def entry_params
        params.require(:entry).permit(:user_id, :room_id)
    end
end #一番上の行に対するend

Routing

routes.rb
(略)
  get 'rooms/new/:id' => 'rooms#new', as:'new_room'
  post 'entry' => 'rooms#room_add_user'
(略)

Views

rooms/show.html.erb
(略)
<%= link_to '参加者を追加する', new_room_path(@room.id) %>
(略)
rooms/new.html.erb
<% if user_signed_in? %>
  <h2>User一覧</h2>
  <% @users.each do |u| %>
    <% if @current_room.entries.pluck(:user_id).exclude?(u.id) %>
      <p><%= u.email %> <%= u.name %>さん</p>
      <%= form_for(@entry, :url => {:controller => :rooms, :action => :room_add_user}) do |f| %>
        <%= f.hidden_field :user_id, :value=> u.id %>
        <%= f.hidden_field :room_id, :value=> @current_room.id %>
        <%= f.submit "追加する" %>
      <% end %>
      <hr>
    <% end %>
  <% end %>
<% end %>

最後に何となく参加中のroom一覧ページ作りました

rooms/index.html.erb
<h1>参加中のroom一覧</h1>
<% if user_signed_in? %>
  <h2>Hello <%= current_user.id %></h2>
  <% current_user.entries.each do |e| %>
    <a href="/rooms/<%= e.room_id %>">
      <%= Room.find(e.room_id).name %>
      <% Room.find(e.room_id).entries.each do |u| %>
        <%= User.find(u.user_id).email %>
      <% end %>
      <br>
    </a>
  <% end %>
  <%= link_to "ログアウト", destroy_user_session_path, :method => :delete %>
<% else %>
  <%= link_to "ユーザーを登録する", new_user_registration_path %>
  <br>
  <%= link_to "ログインする", new_user_session_path %>
<% end %>

<%= link_to "room一覧へ", rooms_path %>
このlink_toで移動できるので適当な場所に書いときましょう!
参考にしたdmの記事が多対多のアソシエーションをしてなくてめんどくさい書き方になっていますが、余力がある方は多対多にしてみると面白いと思います!
それではバイバイ〜

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0