Ruby on Rails jQuery Visual Effect - ruby-on-rails

I am working on a search function on RoR that basically just has a cool visual effect when a user clicks the search button.
Here is the code in my view for search.rhtml
<html>
<head>
<title>Tutor</title>
<%= javascript_include_tag :defaults %>
</head>
<body>
<h1></h1>
<%= form_remote_tag :url =>{ :action => :search_results }, :update => "results" %>
<fieldset>
<legend>Tutor Search.</legend>
<label for="searchItField">Keyword Search.</label>
<input class="tfield" type="text" value="FIND YOUR TUTOR HERE" name="searchItField" id="searchItField" />
<span id="Submit_search">
<span id="Submit_search_hover"><input type="submit" id="Submit" value="Search" /></span>
</span>
</fieldset>
</form>
<div id="results">
</div>
</body>
</html>
Here is the search_results.rhtml which is what gets displayed in the results div in search.rhtml
<% for tutors in #tutors %>
<%= tutors.first_name %> <br/>
<% end %>
And finally here is my controller and actions.
class TutorsController < ApplicationController
def search
end
def search_results
#tutors = Tutors.find_by_sql('SELECT * FROM tutors')
end
end
What I want to do is basically create an effect that when the search results are loaded because of the ajax call that it would slide up. I am using jrails. Exactly how this site does it. http://keyonary.com/#/paste

In short, to get you started, you will need to do the following:
use observe_field on the input-field, which retrieves data from a controller-method and will update a certain div with the results
create a corresponding controller-method that will retrieve the items (use your search_results)
create a view for that controller-method that will show the data with the required effects and animation.

Related

Display Algolia results on product view

I'm new on Ror,
I would like to display on my products.search page all my products cards avalaible, and add an algolia searchbar filtering and displaying results cards instead of all the products on this page.
I know it's not that hard but I don't succeed to make it works.
My algolia index works correctly since I get all my products on Algolia website.
Actually I don't find the good method to put in my controller and the good code to put in my view...:-(
Thk you for your help.
Here is my code:
app.js:
//= require algolia/v3/algoliasearch.min
ProductsController.rb:
def search
#products = Product.where(active: true)
???????
end
Product.rb:
include AlgoliaSearch
algoliasearch if: :active? do
attribute :name, :brand, :category, :color, :size, :price
end
products/search.html.erb:
<!-- Algolia searchbar -->
<!-- HTML Markup -->
<div class="aa-input-container" id="aa-input-container">
<input type="search" id="aa-search-input" class="aa-input-search" placeholder="Trouver un article..." name="search" autocomplete="off" />
<svg class="aa-input-icon" viewBox="XXXXXXXX">
<path d="XXXXXXXXXX" />
</svg>
</div>
<!-- Include AlgoliaSearch JS Client and autocomplete.js library -->
<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
<script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.min.js"></script>
<!-- Initialize autocomplete menu -->
<script>
var client = algoliasearch('XXXXX', 'XXXXXXXXXX');
var index = client.initIndex('Product');
//initialize autocomplete on search input (ID selector must match)
autocomplete('#aa-search-input',
{ hint: false }, {
source: autocomplete.sources.hits(index, {hitsPerPage: 5}),
//value to be displayed in input control after user's suggestion selection
displayKey: 'name',
//hash of templates used when rendering dataset
templates: {
//'suggestion' templating function used to render a single suggestion
suggestion: function(suggestion) {
return '<span>' +
suggestion._highlightResult.name.value + '</span><span>' +
suggestion._highlightResult.category.value + '</span>';
}
}
});
</script>
<div class="col-xs-12 col-md-9">
<% #products.each do |product| %>
<% if product.active? %>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="panel panel-default">
<div class="panel-heading preview">
</div>
<div class="panel-body">
<strong><%= link_to product.name, product %></strong>
<strong><%= product.price %> euros</strong>
</div>
</div>
</div>
<% end %>
<% end %>
</div>
To display Algolia on your current view you can just rely on Front-end search, therefore you can remove the #products = Product.where(active: true) line in your controller and the loop in your view.
That said, your code seems correct. Do you have any records in your Algolia index? If not, you can force the reindexing by using Product.reindex!.

Httparty displaying HTML

I am using httparty gem to get wp-json date from a wordpress site to my Rails application.
Here is my controller that gets the json info:
require 'httparty'
require 'json'
class ConnectionController < ApplicationController
respond_to :json
def index
end
def thirty_days
get_thirty_days
end
private
def query_wordpress_category(wordpress_category)
#response = HTTParty.get("http://thriveconnection.com/wp-json/posts?filter[category_name]=#{wordpress_category}&filter[order]=date")
end
def get_thirty_days
query_wordpress_category("30-days")
#thirty_days = JSON.parse(#response.body)
end
end
Here is what it gets displayed: http://d.pr/i/1jMEq
Here is my view:
<% #thirty_days.each do |article| %>
<div class="row">
<div class="col-md-6">
<a href="<%= article['link'] %>" target="_blank">
<img src="<%= article['featured_image']['source'] %>" alt="" class="img-responsive thumbnail" />
</a>
</div>
<div class="col-md-6">
<strong class="title-font">
<a href="<%= article['link'] %>" target="_blank">
<%= article['title'] %>
</a>
</strong>
<span class="small-font">Published Date <%= article['date'] %></span>
<br /><br />
<%= article['excerpt'] %>
<br /><br />
<a href="<%= article['link'] %>" target="_blank">
<i class="fa fa-bookmark-o"></i>Read the Article
</a>
</div>
</div><!-- END .row -->
<% end %>
Here is my problem, the excerpt from wordpress gets displayed as an html. How can I display that so the HTML tags don't show up. Also, is there any way I can format the date to mm/dd/yyyy format?
You need to mark the strings that you don't want escaped as html_safe which allows the Rails view processor to know not to escape them. Be warned, if you don't escape them then you open your users up to various hack attempts by the other site by including a malicious packet in the strings you retrieve.
So, eg.
<%= article['title'].html_safe %>
Also as for date format I used
<%= Date.parse(article["date"].strftime("%m/%d/%Y") %>

Reading erb form fields, Rails4

Question about Rails4, I trying to retrieve the "Find Stuff" variable, in the erb form. This
is a search field, using zurb foundation - so the extra styling annotations floating around.
I don't have a model as this is just a form for reading the search input field - which is
in the tag, with placeholder as "Find Stuff".
To use normal Rails4 terminology, I would
like to pass the value of the "Find Stuff" field to the salutation controller, and I tried
many ways, but was unsuccessful, when I used render params[:post].inpect, it shows nil -the
variables that I pass to the controller, on clicking on the "Search" link_to, link. I tried adding an id field to the tag, and that too showed nil on render params[:post].inspect.
Any help, thanks in anticipation.
hello.html.erb form below.
<html>
<body>
<nav class="top-bar" data-topbar>
<ul class="title-area">
<li class="name">
<h1>Hello World!</h1>
</li>
<li class="toggle-topbar menu-icon"><span>Menu</span>
</li>
</ul>
<ul class="right">
<li class="has-form">
<div class="row collapse">
<div class="large-8 small-9 columns">
<input type="text" placeholder="Find Stuff" >
</div>
<div class="large-4 small-3 columns">
<%= link_to "", :controller =>
'salutation', :action =>'hello',
:class=>"alert button expand" %>
</div>
</div>
</li>
</ul>
</section>
</nav>
</body>
</html>
Controller follows
Salutation Controller follows
class SalutationController < ApplicationController
def new
#test = ''
end
def hello
#message = 'Hello World!'
#test = params[:Find_Stuff]
end
end
Wrap your search box in a form element, give your input a name and away you go. You can use the rails form helpers as well - see http://guides.rubyonrails.org/form_helpers.html which has a nice intro to creating a search form
<div class="row collapse">
<%= form_tag("/salutation/hello", method: "post") do %>
<div class="large-8 small-9 columns">
<%= text_field_tag(:find_stuff) %>
</div>
<div class="large-4 small-3 columns">
<%= submit_tag("Search") %>
</div>
<% end %>
</div>
Further to #slapthelownote's answer, the reason you're getting an error is because you're not passing any params to your controller
We've got something like what you want working at http://firststopcosmeticshop.co.uk (top search box) -- using a form_tag
If you want to see live code, I'll be happy to post!
Params
Using a form allows you to set various variables & then submit them to the controller as you've set them. I'd recommend using the form in the other answer, but to understand how it works, you need to read up on the Rails forms tutorial
Basically, the params hash is populated in the middleware of Rails -- from any data sent by HTTP to your backend
With links, you can only send GET params (domain.com/route&params=value), whilst with HTML forms, you can set POST params which are passed through the browser (not the URL)

facebook comments plugin to show comments dynamically

i use facebook comments plugin https://developers.facebook.com/docs/plugins/comments/
for every page in my site
and i show the facebook comments by fetching from json request
https://graph.facebook.com/comments/?ids=abc.com/
so when i update comment in facebook plugin, i would like to get the comments in my site to get dynamically updated
my code in controller
#fb_res=HTTParty.get('https://graph.facebook.com/comments/?ids=abc.com/')
fb_json=JSON.parse(#fb_res)
#fb_comment = fb_json["abc.com/"]["comments"]["data"].map {|x| [x["from"]["id"],x["message"],x["from"]["name"]]}
my views :
<% #fb_comment.each do |fb| %>
<li>
<div class="pic_commnt">
<div class="pic">
<div class="pic_image">
<img src="http://graph.facebook.com/<%= fb[0].to_s %>/picture?type=square" alt="" />
</div>
<span class="pic_name"><%= fb[2].to_s %></span>
</div>
<div class="pic_comments">
<p>
"<%= fb[1].to_s %>"
</p>
</div>
</div>
</li>
<% end %>
i would like to get this section updated dynamically

Build templates in views

In grails I do this:
<form:windowEntrada domain="serverPool">
<form:entrada domain="serverLocation" bean="${serverPoolInstance}">
<form:textField label="serverPool.name" name="name" />
<form:select label="serverPool.server" name="server" list="${Servers.list()}"/>
</form:entrada>
</form:windowEntrada>
The tag "form:textField" render something like:
<div class='field-name'>
<div class="title"><label for="name">Name</label>(* required)</div>
<div class="fieldcontent"><input type="text" name="name" value="smtg"></div>
<div class="error">If thereis an error on this field, the message appears here</div>
</div>
The tag "form:windowEntrada" render something like:
<div class='container'>
<h1>My title here</h1>
<div class="content">${body()}</div>
</div>
The tag "form:entrada" render something like:
<form action ... >
<....> --> messages stuff
${body()}
<div class="action-buttons">
<input type="submit" name="lala">
<input type="submit" name="lala2">
</div>
</div>
How can I do i rails using erb as my view tecnology?
Thank you.
I Have found the answer here: pathfindersoftware.com/2008/07/pretty-blocks-in-rails-views
Here's an example applying the tutorial:
In ERB:
<%= widget("mytitle", {:class => "widget-table"}) do %>
test test test
<% end %>
in the helper:
def widget(title, options = {}, &block)
options[:params] = params
options[:controller_name] = controller.controller_name
body = capture &block
html = render "shared/form/widget", :body => body,
:title => title,
:options => options
return html
end
and the template _widget.html.erb:
<div class="widget <%= options[:class] unless options[:class].blank? %>">
<% unless title.blank? %>
<div class="widget-header">
<span class="icon-layers"></span>
<h3><%= title %></h3>
</div>
<% end %>
<div class="widget-content">
<%= body%>
</div>
</div>
tks

Resources