Omar Khedr

Joined

7,960 Experience
46 Lessons Completed
4 Questions Solved

Activity

Posted in Symbols vs Strings Discussion

Amazing video!! Thank you so much Chris for these basic/general courses - more of these would be incredile!

Posted in How to use Uppy with ActiveStorage Discussion

@henry did you ever get to work - i got the same issue :'(

Posted in Is there an episode on Post Production Updates?

Love the latest episodes Chris! Was wondering if you have or plan to cover soon how to do post production updates on a rails app. For me that is a scary topic and one i think lots of folks would love to do. I can adjust my app in development but once i push to production, I'm stuck on how to do updates to it - like adding new models, controllers, or view pages

Chris great video!! How did you know to leverage Port 8082 instead of Port 8080?

Love this episode!! Thanks Chris! Question though are there any disadvantage in using geocoder? And instead relying on Google Maps Javascript API?

Found the correct way that worked, leaving the code below in case anyone else needs help with it.

Index.html.erb

<div class="col-md-4">
                     <form name="searchBox" onsubmit="return searchFunction(this);">
                    Search for a User: <input type="text" name="keyword" />
                    <input type="submit" value="Search"/>
            </form>

            <div class='searchHints' style="display:none;">
              <span>No results</span>
            </div>

                <% (User.all - [current_user]).each do |user| %>
                    <div class="box2 searchable" style="display:all" data-username="<%= user.username %>">
                                <%= image_tag user.background, height: 95, width: 165, class: "css-style4"   %>
                                <div class="row">
                                <div class="col-md-4">      
                                    <%= image_tag user.avatar, height: 60, width: 55, class: "css-style5"   %>
                                </div>
                                <div class="col-md-6">
                                </div>
                                <div class="col-md-2">
                                </div>
                                </div>
                                <strong><%= link_to user.username, direct_message_path(user.id), data: {behavior: "chatroom-link", chatroom_id: Chatroom.direct_message_for_users([current_user, user]).id} %></strong>
                    </div>  
                <% end %>
                </div>

chatroomsearch.js

function searchFunction(elem) {
    var keyword, $searchableElements, $filteredElems;

    keyword = $(elem).find('input[name="keyword"]').val();
    $searchableElements = $(".searchable");

    $searchableElements.hide();
    $('.searchHints').hide();

  var $filteredElems= $searchableElements.filter(function(index, element){
    return (new RegExp(keyword, 'i')).test(element.dataset.username);
  })

  if($filteredElems.length > 0) {
    $filteredElems.show();
  } else {
    $('.searchHints').show();
  }

  return false;
}

I'm trying to set up a simple search bar to show/hide content in my rails app. Specifically, trying to allow someone to search for a specific user via username in my chatroom which are being shown using a Rails each array. I looked at these two SO questions for guidance but still didn't get it to work - https://stackoverflow.com/questions/6709718/in-page-search-using-contains-to-show-hide-div-content and https://stackoverflow.com/questions/34353009/dynamical-search-function-to-show-hide-divs. Whenever, I type a user's name though in my search box nothing appears. I have listed my code below and any help on this matter would be amazing. Thank you so much!

Index.html.erb

<div class="col-md-4">
 <form name="searchBox">
   Search for a User: <input type="text" name="keyword" />
   <input type="button" value="Search" onClick="searchFunction()" />
</form>
<% (User.all - [current_user]).each do |user| %>
<div class="box2" style="display:none" id="searchable">
            <%= image_tag user.background, height: 95, width: 165, class: "css-style4"   %>             
            <strong><%= link_to user.username, direct_message_path(user.id), data: {behavior: "chatroom-link", chatroom_id: Chatroom.direct_message_for_users([current_user, user]).id} %></strong>
</div>
<% end %>
</div>

chatroomsearch.js

function searchFunction() {
$("#searchable")
    .hide()
    .filter(":contains('" + $("input[name='keyword']").val() + "')")
    .show();
}

Posted in Rails How to link an email form with Sendgrid?

I was able to create a contact form that when a user clicks submit - its send an email (which i get in my yahoo inbox).

I would like to now have that email be sent via sendgrid so that I can analyze analytics. I looked at the Gorails Sendgrid course and was able to send an email via sendgrid through his example but I don't know how to apply that now to my contact form. I have listed my code below, any help would be amazing. Thank you so much!

new.html.erb (Contact Form which sends an email regularly when a user clicks submit)

<div align="center">
<h3>Send A message to Us</h3>
  <%= form_for @contact do |f| %>
<div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name, :required => true %>
</div>
<div class="field">
    <%= f.label :email %><br>
    <%= f.email_field :email, :required => true %>
    </div>
    <div class="field">
    <%= f.label :message %><br>
    <%= f.text_area :message, :as => :text, :required => true %>    
</div>
<div class="actions">
    <%= f.submit "Send Message", :class => "btn btn-primary btn-md"%>
    </div>
  <% end %>
</div>

contacts_controller.rb

class ContactsController < ApplicationController
  def new
@contact = Contact.new
  end
  def create
@contact = Contact.new(contact_params) 
@contact.request = request
if @contact.deliver
  flash.now[:notice] = 'Thank you for your message. We will contact you soon!'
else
  flash.now[:error] = 'Cannot send message.'
  render :new
end
  end
  private
  def contact_params
  params.require(:contact).permit(:name, :email, :message)
  end
end

Sendgrid.rb (Within my config > initializers folder)

ActionMailer::Base.smtp_settings = {
  :user_name => 'apikey',
  :password => Rails.application.secrets.sendgrid_api_key,
  :domain => 'tango.co',
  :address => 'smtp.sendgrid.net',
  :port => 587,
  :authentication => :plain,
  :enable_starttls_auto => true
}

development.rb

config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey',
:password => Rails.application.secrets.sendgrid_api_key,
:domain => 'tango.co',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}

Mailers Folder (I only have two files Notification and application none deal with my Contacts Form)

Gary I tried bundle update and that didn't work, I thought about installing an earlier version of rails would you recommend that?

Hi everyone,
I was working through Chris refile gem course and trying to implement it into my app. When I tried to do bundle install, I kept running into an error message in my console saying that bundle could not find compatible versions for my gem "rack" (screenshot of error below). I tried looking at these Stackoverflow questions - https://stackoverflow.com/questions/40284591/bundler-could-not-find-compatible-versions-for-gem-rack-in-gemfile and https://stackoverflow.com/questions/22704671/bundler-could-not-find-compatible-versions-for-gem-rack without success. I tried multiple approaches - 1. putting rack in my Gemfile, 2. uninstalling all previous rack and then installing rack versions. None seemed to work. And this issue only appears when I have inserted "gem "refile", require: "refile/rails" &
gem "refile-mini_magick"; when I remove these two gems my gemfile can be bundle installed without issue. I would greatly appreciate any help on this issue. Thank you so much.

When I run Bundle Install

When I then run Bundle Update

Posted in Global Autocomplete Search Discussion

Chris thank you for this video, super helpful! I get a strange error though when following you at the end. In my navbar page - "undefined method `form_with' for #<#<class:0x007f875a6f8b58>:0x007f87600e0aa8>" I decided to hack away and switch form_with for form_tag but then I get an error on the line immediately below "undefined method `text_field' for nil:NilClass" I double checked my code and don't know what could be causing it. Any help would be amazing sir thanks :)
Github: https://github.com/OmarZV/s...

Researched, hacked through trial and error but was finally able to get it to work. If anyone else has a similar issue, I've outlined what worked for me below.

Three Steps

Add a post to your routes file so that a user can go to the search results page.
post 'books/search' => 'books#search', as: 'search_books'

2.Adjust your form_tag on your application.html.erb so that it can properly point to your search results page

<%= form_tag search_books_path do %>
<%= text_field_tag :q, nil, placeholder: "Search..." %>
<% end %>

In your search.html.erb make sure to list out your search results
<% @booksearches.each do |booksearch| %>

<%= link_to booksearch.title, booksearch %>


<% end %>

I just finished going over Chris's two great railscasts dealing with search. However, I wanted to put my search bar on my navbar so that whenever someone searches the results I will be taken to my search.html.erb within my books folder (similar to how Gorails works). I ran into an issue though, everytime I did a search I was taken to my books page [http://localhost:3000/books?utf8=%E2%9C%93&q=travel] with no results being shown just my standard index showing all my books and was never taken to my search results page. I've listed all my relevant code below. If anyone can help me out would be super grateful. Thank you guys so much!

Book.rb

class Book < ApplicationRecord
    has_many :likes, :counter_cache => true
    has_many :users, through: :likes

    searchkick
    end

books_controller.rb

class BooksController < ApplicationController
    before_action :authenticate_user!, only: [:new, :create]
  before_action :set_book, only: [:show, :edit, :update, :destroy, :share]

    def index
        @books = Book.all
    end

    def search
    @booksearches = Book.search(params.fetch(:q, "*"))
    end

    private
      def set_book
      @book = Book.find(params[:id])
    end

    def book_params
      params.require(:book).permit(:title, :author, :avatar)
    end

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

def search
    @booksearches = Book.search(params.fetch(:q, "*"))
  end

    end

application.html.erb

<!DOCTYPE html>
<html>
  <head>   
    <%= csrf_meta_tags %>    

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   </head>

  <body style="background-color: #f5f8fa; padding-top: 70px;" class="<%= @body_class %>">
<nav class="navbar navbar-default navbar-fixed-top">
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li>
                <%= form_tag books_path, method: :get do %>
                    <%= text_field_tag :q, nil, placeholder: "Search..." %>
                <% end %>
            </li>         
          </ul>
            </div>
        </nav>
    </body>
</html>

Posted in Finding Users in Group Chat Go Rails Class

Was able to figure it leveraging the great SO commnity. In case anyone else is stuck on a similar issue, here's a link to the solution that worked

(http://stackoverflow.com/questions/44092682/find-all-chatrooms-associated-with-a-current-user-using-group-chat-via-actioncab)

Posted in Finding Users in Group Chat Go Rails Class

Hi guys,

I went through Chris's Go Rails course on Group Chat with Action Cable and learned loads from it. One of the things that I need some help with though is being able to find all the chatrooms associated with a current user and displaying it in my html page. I tried the following but this only gave me my currently displayed direct_message page.

My Attempt - show.html.erb

<% @chatroomall.each do |chatroom| %>
<div>
<%= @chatroom.name %>
</div>
<% end %>

direct_messages_controller.rb

class DirectMessagesController < ApplicationController
    before_action :authenticate_user!

    def show
        users = [current_user, User.find(params[:id])]
        @messageduser = User.find(params[:id])
        @chatroom = Chatroom.direct_message_for_users(users)        
        @chatroomall = Chatroom.all
        @messages = @chatroom.messages.order(created_at: :desc).limit(100).reverse
        @messagelast = @chatroom.messages.last(1)
        render "chatrooms/show"
    end
    end

Chatrooms.rb

class Chatroom < ApplicationRecord
    has_many :chatroomusers
    has_many :users, through: :chatroomusers
    has_many :messages

    scope :public_channels, ->{where(direct_message: false) }
    scope :direct_messages, ->{ where(direct_message: true) }

    def self.direct_message_for_users(users)
        user_ids = users.map(&:username).sort
        name = "#{user_ids.join(" and ")}"

        if chatroom = direct_messages.where(name: name).first
            chatroom
        else

            chatroom = new(name: name, direct_message: true)
            chatroom.users = users
            chatroom.save
            chatroom
        end

    end
end

This worked amazing thank you so much Jack for pointing me in the right direction :) In case anyone else looks at Chris' source code - it works amazing the one thing is depending on your text editor you might want to do this for the bootstrap button --> or else you'll get a editor error message (I use UltraEdit)
Close

I apologize for the newbie question. But, I've been trying to create a special type of association and all my efforts have been failing. I would like to give users the ability to select their home cities. I've put down a few options from which they can choose, but if its not currently in the list - I would like a User to simply be able to add it "Don't see your City, add it". Then another User who signs up later can see the new city in his list (I know I might have to handle duplicate requests so any tips would be amazing). I've listed all my relevant code below. Thank you so much!

HomeCity Migration

class CreateHomecities < ActiveRecord::Migration[5.0]
  def change
    create_table :homecities do |t|
      t.string :Hometown

      t.timestamps
    end
  end
end

HomeCity Reference to Users

class AddHomecitiesRefToUsers < ActiveRecord::Migration[5.0]
  def change
    add_reference :users, :homecity, foreign_key: true
  end
end

User.rb

class User < ApplicationRecord
  cattr_accessor :current_user
  belongs_to :homecity, optional: true
end

Homecity.rb

class Homecity < ApplicationRecord
  has_many :users
end

Edit.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
  <%= f.label :homecity %>
  <br>
  <%= f.collection_select :homecity_id, Homecity.all, :id, :Hometown %>
</div>
<div class="form-group">
  <%= f.submit "Update", class: 'btn btn-lg btn-block btn-primary' %>
</div>
<% end %>             

Seeds.rb

Homecity.destroy_all
bigapple = Homecity.create!(Hometown:"New York City")
techhub = Homecity.create!(Hometown:"San Francisco")
longhorns = Homecity.create!(Hometown:"Austin")
angels = Homecity.create!(Hometown:"Los Angeles")
windycity = Homecity.create!(Hometown:"Chicago")

Homecities_controller.rb (Created new controller file based on research)

class HomecitiesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
def new
 @homecity = Homecity.new
end
def create
 @homecity = Homecity.new(homecity_params)
end
private
def homecity_params
 params.require(:homecity).permit(:user_id)
end
end

Example similar to how Facebook does it with Education

Posted in Getting an simple Ajax request on Rails

Solved the issue - The problem was 4 fold: Turbolinks, my controller file for forum_threads, index.json.jbuilder, and my coffescript file. Hope it helps someone else learning. I have provided the answer in SO in case anyone else is stuck in a similar issue.
http://stackoverflow.com/questions/41024125/simple-ajax-request-with-rails-bootstrap

Posted in Getting an simple Ajax request on Rails

Hey guys, just went through the Notifications videos. To see if I understood the concepts correctly, I tried doing my own solo Ajax request on the forum_threads instead of Notifications.

I ran into a roadblock though because I'm only returning an empty [ ] when I do /forum_threads.json I think the issue is in either my controller under index which is as follows.

def index
    @forum_threads = ForumThread.all
    @forum_threads = ForumThread.where(id: :ForumThread_id)
  end

Or in my super simple json.jbuilder which I did by as such:

json.array! @forum_threads do |forum_thread|
    json.url forum_thread_path(forum_thread)
end

If you can help me out would be super helpful. Thank you so much guys :)

Github to the Code: https://github.com/OmarZV/NotificationAjax

Posted in Inviting Users with devise_invitable Discussion

Chris great episode, thank you so much! One question, everything works great on my end. But, the emails don't actually reach their destinations. Is that because we are in development or do we need to have something extra installed in our app? Thanks mate!

logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.