Wednesday, 7 December 2016

search users and comment

1. search form-index

<form>
  <%= form_tag '/users', :method => 'get' do %>
  <p>
    <%= text_field_tag :title, nil, :placeholder=>"search users",:class=>"jjj" %>
    <%= submit_tag "search"%>
  </p>
<% end %>
</form>

controller:-

def index
    if params[:title].present?
      @users = User.where("columnname like ?", "%#{params[:title]}%")
    else
     @users = User.all
    end
  end

search comment:

form:

<%= form_tag "/events/#{@event.id}", :method => 'get', remote: true do %>
 <p>
   <%= text_field_tag :name, nil, :placeholder=>"search comment",:class=>"" %>
   <%= submit_tag "search"%>
 </p>
<% end %>

controller:

def show
  if params[:name].present?
      @comments = Comment.where("name like ? AND event_id = ?", "%#{params[:name]}%", @event.id).order("created_at DESC")
    else
      @comments = Comment.where(:event_id =>  @event.id)
    end
    respond_to do |format|
      format.js{ render 'comment'}
      format.html  
    end
end

Comment like:

routes:
 get 'like' =>'comments#like', as: :like
  get 'unlike' =>'comments#unlike', as: :unlike

def like
    @comment = Comment.find(params[:comment_id])
    @like = Like.create(:likeable_id=>params[:comment_id], :likeable_type=>"Comment", :user_id=>current_user.id)
    # UserMailer.welcome_email(@comment).deliver_now
    @event = Event.find(@comment.event_id)
    redirect_to event_path(@event)
  end

  def unlike
    @comment = Comment.find(params[:comment_id])
    # @like = Like.where(:comment_id=>params[:comment_id], :user_id=>current_user.id).first
    @like = @comment.likes.first
    @like = @like.destroy
    @event = Event.find(@comment.event_id)
    redirect_to event_path(@event)
  end

Views: 

<% @comments.each do |comment|%>
<p>
 <strong>Name:</strong>
 <%= comment.name %>
</p>
<% if !Like.where(:likeable_id=>comment.id, :user_id=>current_user.id).present? %>
<%= form_tag '/like', :method => 'get', remote: true do %>
<%= hidden_field_tag "comment_id" ,nil ,:value => comment.id%>
<p>
 <%= submit_tag "like(#{comment.likes.count})", :name => nil %>
 </p>
<% end %>
<%else%>
<%= form_tag '/unlike', :method => 'get', remote: true do %>
<%= hidden_field_tag "comment_id" ,nil ,:value => comment.id%>
<p>
 <%= submit_tag "unlike(#{comment.likes.count})", :name => nil %>
</p>
    <% end %>
<%end%>
<%end%>


Comment without controller:

def comment_index
   @comments = Comment.all
 end
 def comment_show
   @comment = Comment.find(params[:id])
 end
 def comment_edit
   @comment = Comment.find(params[:id])
 end
 def comment_new
   @comment = Comment.create(:name=>params[:name], :description=>params[:description], :event_id=>params[:event_id])
 end
 def create_comment
   @event = Event.find(params[:event_id]) @comment = Comment.create(:name=>params[:name], :description=>params[:description], :event_id=>@event.id) redirect_to event_path(@event)
 end

No comments:

Post a Comment