Sunday, 29 September 2013

Message chat for rails using ajax

In message controller.rb


class MessagesController < ApplicationController
  # GET /messages
  def index
   @messages=Message.all
    @raj=Message.new
  end

  def create
    @message = Message.create!(params[:message])
  end
end

In messages/index.html

<h2>Chat</h2>

<ul style="background-color:#aaaaaa;width: 100px;border:1px solid blueviolet;" id="chat">
  <%= render :partial => @messages%>
</ul>

<div id="message_form">
<%= form_for(@raj, :remote=>true) do |f| %>
  <div class="field">
    <%= f.text_field :content %>
  </div>
  <div class="actions">
    <%= f.submit 'Send' %>
  </div>
<% end %>
</div>

In messages/_message.html.erb

<%= content_tag_for(:li, message) do %>
  <%= message.content %>
<% end %>

In messages/create.js.erb

$('#chat').append('<%= escape_javascript(render(@message)) %>');
$("#message_form")[0].reset();

No comments:

Post a Comment

Interactor in Rails

What is interactor? Interactor provides a common interface for performing complex user interactions An interactor is a simple, sin...