Rails 5.2 can not pagination with kaminari and notifications - notifications

Some of my gemfiles :
gem 'rails', '~> 5.2'
gem 'notifications', '~> 0.6.0'
gem 'kaminari'
My notifications_controller.rb like this:
# notifications_controller.rb
module Notifications
class NotificationsController < Notifications::ApplicationController
def index
#notifications = notifications.includes(:actor).order("id desc").page(params[:page])
unread_ids = #notifications.reject(&:read?).select(&:id)
Notification.read!(unread_ids)
#notification_groups = #notifications.group_by { |note| note.created_at.to_date }
end
def clean
notifications.delete_all
redirect_to notifications_path
end
private
def notifications
raise "You need reqiure user login for /notifications page." unless current_user
Notification.where(user_id: current_user.id)
end
end
end
My routes.rb about notifications like this :
mount Notifications::Engine, at: "notifications"
My index.html about notifications like this:
# notifications/notifications/index.html.erb
<div class="paginationBox">
<%= paginate #notifications,left:2,right:1,window: 1 %>
</div>
With the above codes , I can get the right notifications , but I can not paging the all notifications. I had the error like this:
NoMethodError - undefined method `total_pages' for #<Notification::ActiveRecord_Relation:0x00007fcfacae6dd8>:
app/views/notifications/notifications/index.html.erb:33:in `_app_views_notifications_notifications_index_html_erb__2430601159943313679_70264929101860'
If I change the action index of notifications_controller.rbto
#notifications = notifications.includes(:actor).order("id desc").page(params[:page]).per(10)
I get the same error undefined method total_pages....
If I just change the index.html.erb of notificaitons to
<div class="paginationBox">
<%= paginate#notifications.page(params[:page]).per(10),left:2,right:1,window: 1 %>
</div>
It does not display any errors ,but the kaminari can not paging the all notifications .
So ,where did I had the errors? Could you please help me ? Thanks so much!

Related

Rails get random yoda giphy API image to show on 'welcome/yoda'

I got the translate yoda API to work from mashape. https://github.com/sfinley89/BEWD_midcourse
Now Im trying to get random yoda giphy images to show up on the 'welcome/yoda' page when their text is translated into yoda speak.
Here is what im getting right now showing on the 'welcome/yoda'
Yoda Says, "Lets gets some gifs alrady. "
#<Giphy::RandomGif:0x007ffae5467e08>
#<unirest::httpresponse:0x007ffae57a23e8>
{"data"=>{"type"=>"gif", "id"=>"PciMitIKp0UjS", "url"=>"http://giphy.com/gifs/yoda-PciMitIKp0UjS", "image_original_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.gif", "image_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.gif", "image_mp4_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.mp4", "image_frames"=>"21", "image_width"=>"150", "image_height"=>"190", "fixed_height_downsampled_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/200_d.gif", "fixed_height_downsampled_width"=>"158", "fixed_height_downsampled_height"=>"200", "fixed_width_downsampled_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/200w_d.gif", "fixed_width_downsampled_width"=>"200", "fixed_width_downsampled_height"=>"253", "fixed_height_small_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100.gif", "fixed_height_small_still_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100_s.gif", "fixed_height_small_width"=>"79", "fixed_height_small_height"=>"100", "fixed_width_small_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100w.gif", "fixed_width_small_still_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100w_s.gif", "fixed_width_small_width"=>"100", "fixed_width_small_height"=>"127", "username"=>"", "caption"=>""}, "meta"=>{"status"=>200, "msg"=>"OK"}}
Back
How do I get this to show the random yoda gif?
Here is my controller welcome_controller.rb
class WelcomeController < ApplicationController
def index
#ask
end
def ask
end
def yoda
##voice = HTTParty.get('https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait.').parsed_response
#sentence = "You+will+learn+how+to+speak+like+me+someday.++Oh+wait."
sentence = params[:sentence]
#render plain: ENV["YODA_KEY"]
#response = Unirest.get "https://yoda.p.mashape.com/yoda?sentence="+sentence,
headers:{
"X-Mashape-Key" => ENV["YODA_KEY"],
"Accept" => "text/plain",
}
#gifpic = Unirest.get "http://api.giphy.com/v1/gifs/search?q=Yoda&api_key=dc6zaTOxFJmzC"
#gif = Giphy.random('Yoda')
url = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=yoda"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
#result = JSON.parse(buffer)
end
end
Here is my welcome/index.html.erb
<center>
<h2>Midcourse Project</h2><br>
<br>
<%= link_to "Ask Yoda How He Would Say It!", 'welcome/ask' %>
<br><br><br><br><br><br>
<%= image_tag "http://www.extension.zone/wp-content/uploads/2015/05/Giphy-logo.jpg", size: "200x100", :alt => 'logo' %>
</center>
Here is welcome/ask.html.erb
<center>
<h1> I am yoda! What do you want me to say? </h1><br>
<%= form_tag "/welcome/yoda" %>
<%= text_field_tag :sentence %>
<%= submit_tag "Submit" %>
</center>
Here is welcome/yoda.html.erb
<p> Yoda Says, "<%= p #response.raw_body %>"</p> <br>
<%= #gif %> <br>
<%= image_tag #gifpic %> <br>
<%= p #result %>
<br>
<%= link_to "Back", '/welcome/ask' %>
Here is my gemfile
source 'https://rubygems.org'
# unirest http://unirest.io/ruby
gem 'unirest', '~> 1.1', '>= 1.1.2'
# HTTParty
#gem 'httparty', '~> 0.13.7'
# Gem from https://rubygems.org/gems/giphy/versions/3.0.0
# gifs https://github.com/sebasoga/giphy
gem 'giphy', '~> 3.0'
# Geocoding https://github.com/alexreisner/geocoder
gem 'geocoder'
# Yelp https://github.com/Yelp/yelp-ruby
gem 'yelp', require: 'yelp'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
And here is the routes.rb
Rails.application.routes.draw do
# get the yoda page
get 'welcome/yoda'
# post to the yoda page
post 'welcome/yoda'
# get the ask page
get 'welcome/ask'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'welcome#index'
end
Documentation:
on github checkout /Giphy/GiphyAPI
or /sebasoga/giphy
Please help me out with this.
Answer: <%= image_tag #result["data"]["image_url"] %> put this in your views where you want it displayed.
Change controller welcome_controller.rb to look like
class WelcomeController < ApplicationController
def index
#ask
end
def ask
end
def yoda
##voice = HTTParty.get('https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait.').parsed_response
#sentence = "You+will+learn+how+to+speak+like+me+someday.++Oh+wait."
sentence = params[:sentence]
#render plain: ENV["YODA_KEY"]
#response = Unirest.get "https://yoda.p.mashape.com/yoda?sentence="+sentence,
headers:{
"X-Mashape-Key" => ENV["YODA_KEY"],
"Accept" => "text/plain",
}
url = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=yoda"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
#result = JSON.parse(buffer)
end
end
Change view welcome/yoda.html.erb to look like
<p> Yoda Says, "<%= p #response.raw_body %>"</p> <br>
<%= image_tag #result["data"]["image_url"] %>
<br>
<%= link_to "Back", '/welcome/ask' %>

submitting form using remote: true in rails not working

This is my view
<%= form_tag url_for(action: :comt, id: #com.id), remote: true do |f| %>
<textarea name="inst">test</textarea>
<button class="small" id="btn">Submit</button>
Here is my controller:
def comt
id= params[:id]
#com = comment.find id
if #com.update_attribute(:instruction, params[:inst])
redirect_to action: :index
end
end
It is working correctly but i need it using ajax.
If i remove redirect_to it throwing error message. Where i am wrong. Can anyone correct it.

Recaptcha with devise is not working on ruby on rails?

I get this error:
There has been an unexpected error with the application. Please contact the administrator. error code: success
I am using recaptcha with devise, I edited where appropriate as stated by following the steps mentioned on this page
Here is my Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'json'
gem 'execjs'
gem 'therubyracer'
gem 'will_paginate', "3.0.pre4"
group :production do
gem 'pg'
end
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
gem 'jquery-fileupload-rails'
gem "letter_opener"
gem 'jquery-ui-rails'
end
gem 'jquery-rails'
gem "carrierwave"
gem "fastercsv"
gem 'devise', '2.1.2'
gem 'rmagick'
gem 'mailman', :require=> false
gem 'activeadmin'
gem 'kaminari'
gem 'prawn'
gem 'recaptcha', :require => 'recaptcha/rails'
I hope you have followed it exactly what it says on the documentation For instance, to support recaptcha on ruby 1.8.X and 1.9.X, there are different line of code. However, after a short research I found out this website you can use recaptcha without the plugins regardless of your rails version. I hope this helps. :)
From Recaptcha Site (almost).... I'm in Rails 4 with Devise (aparently the hard bundle).. No, is too easy. Procedure apply to any ruby, any rails, and devise (or without devise). Tested in ruby/rails/devise 1.9.3/3.2.x/2.2.1 & 2.0.x/4.0.x/3.2.4 and last one without Devise.
Edit next files:
Gemfile
gem 'ruby-recaptcha'
# bundle install
config/initializers/credentials.rb (any file in this path it's ok)
# Set constants
RCC_PUB = "your_public_key"
RCC_PRIV= "your_private_key"
# re-start server. Try to keep safety this data using ENV vars.
app/views/devise/registrations/new.html.erb (or form you prefer)
# form
<%= simple_form_for(resource, as: resource_name, :url => registration_path(resource_name) do |f| %>
<%= f.input :email, autofocus: true, required: true %>
...
<!-- Add next line -->
<div id="captchadiv"></div>
<%= f.button :submit, "Register", class: 'btn btn-danger' %>
<% end %
At the end of same file (can be in awesome_funcs.js.erb file)
<script type="text/javascript" charset="utf-8">
$(function () {
function showRecaptcha() {
Recaptcha.create("<%= RCC_PUB %>", "captchadiv", {
theme: "white",
lang: 'en'
});
};
showRecaptcha();
});
</script>
And the little trick, app/controllers/application_controller.rb
# On top
include ReCaptcha::AppHelper
before_action :configure_permitted_parameters, if: :devise_controller?
# If already you have this method or any other with before_filter
# Into method
protected
def configure_permitted_parameters
if controller_name == "registrations" && action_name == "create"
# Rails 3: If you prefer, put this into registrations#create method
unless validate_recap(params, User.new.errors) # Or your model
# wrong input is handled here
flash[:error] = "Text from images doesn't match with your input"
redirect_to :back # or other stuff
# As my submit is with Ajax, I do a render instead redirect:
# render :json => {other: "recaptcha_failed"}
# In success callback I evaluate response and Recaptcha.reload() paints a new recaptcha.
end
end
....
# trick: do everything before params sanitizers
end
As we are using Ajax plugin, finally, add in
app/views/layouts/application.html.erb
(just before end of body)
<body>
...
...
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
</body>
That's it. You have recaptcha
Advice:
If you use Ajax to do submit, you can use success callback for a Recaptcha.reload() in case images and input doesn't match.
Other, if your form is "remote: true", you can use above behavior after "create" method in create.js.erb file in your views directory.
IMPORTANT: In some projects when form arrives from a link Recaptcha doesn't appear. Try to locate the launcher link into a div or in a parent div add "data-no-turbolink". I had this issue in Rails 4.

Rails: redirect_to with :error, but flash[:error] empty

I'm trying to do a redirect while setting the flash[:error] value. (Rails 3.0.10)
In my view I have
<p id="error"><%= flash[:error] %></p>
<p id="notice"><%= flash[:notice] %></p>
If I do a redirect_to show_path, :notice => "ok" it works fine, but if I do redirect_to show_path, :error => "error" it doesn't show up.
what could I be missing?
As stated in the Rails API only :notice and :alert are by default applied as a flash hash value. If you need to set the :error value, you can do it like this:
redirect_to show_path, flash: { error: "Insufficient rights!" }
If you are having problem to keep the flash after redirecting to another path, then use this.
flash.keep
in your method, before redirecting.
To truly follow the PRG pattern, I wonder if this project works well
https://github.com/tommeier/rails-prg
I can't stand apps not following PRG as a user.....I have been 6 pages after a POST and hit the back button to get back to 10 pages ago get blocked by "do you want to repost this crap"....no, of course not. I just want to get back to a page I had seen before.
non-PRG apps are very very annoying to users.
controller.rb
flash[:sucess] = "Your sucess message"
redirect_to action: :index
layout.html
<% if flash[:sucess] %>
<div class="alert alert-solid-success alert-bold" role="alert">
<div class="alert-text"><%= sanitize(flash[:sucess]) %></div>
</div>
<% end %>

Ambethia Recaptcha Validation

I have the following code in my controller:
#video=Video.find(params[:id])
#video.increment!(:votes)
respond_to do|format|
format.js
This works fine.I want to add recaptcha validation to it.Iam using Ambethia recaptcha.
Add gem 'recaptcha', :require => 'recaptcha/rails' to your Gemfile, run bundle
Create your reCAPTCHA keys: https://www.google.com/recaptcha/admin/create
Add the public and private key to your project and restart your server:
config/initializers/recaptcha.rb
Recaptcha.configure do |config|
config.public_key = 'xxx'
config.private_key = 'yyy'
end
in your view:
<%= recaptcha_tags %>
in your controller:
def create
if verify_recaptcha
else
end
end