I try to use calendar api from google for flatsharing application in Ruby On Rails that we are making in bootcamp.
A can only access to my calendars, but I want to create a shared calendar for all roommates with the possibility adding events. I can really use some help.
I have this Rails error : Unexpected error: #<ArgumentError: Missing authorization code.>
pages controller
class PagesController < ApplicationController
skip_before_action :authenticate_user!
def home
end
def redirect
client = Signet::OAuth2::Client.new(client_options)
redirect_to client.authorization_uri.to_s, allow_other_host: true
end
def client_options
{
client_id: ENV["google_client_id"],
client_secret: ENV["google_client_secret"],
authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
scope: Google::Apis::CalendarV3::AUTH_CALENDAR,
redirect_uri: callback_url
}
end
def callback
client = Signet::OAuth2::Client.new(client_options)
client.code = params[:code]
response = client.fetch_access_token!
session[:authorization] = response
redirect_to calendars_url
end
def calendars
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
#calendar_list = service.list_calendar_lists
rescue Google::Apis::AuthorizationError
response = client.refresh!
session[:authorization] = session[:authorization].merge(response)
retry
end
def events
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
#event_list = service.list_events(params[:calendar_id])
end
def new_event
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
today = Date.today
event = Google::Apis::CalendarV3::Event.new({
start: Google::Apis::CalendarV3::EventDateTime.new(date: today),
end: Google::Apis::CalendarV3::EventDateTime.new(date: today + 1),
summary: 'New event!'
})
service.insert_event(params[:calendar_id], event)
redirect_to events_url(calendar_id: params[:calendar_id])
end
end
My routes
get '/redirect', to: 'pages#redirect', as: 'redirect'
get '/callback', to: 'pages#callback', as: 'callback'
get '/calendars', to: 'pages#calendars', as: 'calendars'
get '/events/:calendar_id', to: 'pages#events', as: 'events', calendar_id: /[^\/]+/
post '/events/:calendar_id', to: 'pages#new_event', as: 'new_event', calendar_id: /[^\/]+/
And my view
<div class="container">
<ul>
<% #calendar_list.items.each do |calendar| %>
<li><%= calendar.summary %> (<%= calendar.id %>)</li>
<% end %>
</ul>
<ul>
<% #event_list.items.each do |event| %>
<li><%= event.summary %> (<%= event.id %>)</li>
<% end %>
</ul>
<%= form_tag new_event_url do %>
<%= submit_tag 'Add event' %>
<% end %>
</div>
And I tried to follow this tutorial : https://readysteadycode.com/howto-integrate-google-calendar-with-rails
Related
When I write city in field and click button, on page has to be that name of city and another. In my case every time name is New York. When I write for example Las Vegas my link is http://localhost:3000/?query=Las+Vegas&commit=Search, the data on the page is about New York.
class HomeController < ApplicationController
def index
require 'net/http'
require 'json'
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
#uri = URI("http://api.weatherstack.com/current?access_key=1dbc1a3aa6b2e76a0c8eda1cba0c9c8b&query=#{#params[:query]}")
#uri.query = URI.encode_www_form(#params)
#json = Net::HTTP.get(#uri)
#api_response = JSON.parse(#json)
if #params[:query].empty?
#city = "Enter city"
#temperature = "(in English)"
else
#city = " #{#api_response['location']['name']}"
#temperature = "#{#api_response['current']['temperature']}°"
end
end
end
routes.rb
Rails.application.routes.draw do
root 'home#index', :as => 'search'
end
index.html.erb
<div class="main">
<h1 class="weather">Weather</h1>
<%= form_with(url: search_path, method: "get", local: true) do %>
<%= text_field_tag(:query) %>
<%= submit_tag("Search",class: "btn btn-primary") %>
<% end %>
<div class="city"> <h1><%= #city %> <h5><%= #temperature %></h5></h1> </div>
</div>
It looks like you have hardcoded New York in your params.
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
So you need to change this to be something like:
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => params[:query]
}
I am trying to integrate stripe into my rails app. Everything works well until I submit the form in which it looks like this when I do so:
Once I submit the form I am getting the following error:
I cannot figure out why it is doing this. When I check my stripe test dashboard nothing is there.
Here are some of the files:
donation.html.erb
<%= form_tag charges_path do %>
<div id="error_explanation">
<% if flash[:error].present? %>
<p><%= flash[:error] %></p>
<% end %>
</div>
<article>
<%= label_tag(:amount, 'Donation Amount:',class: 'donationHead') %>
<%= text_field_tag(:amount,"", class: 'form-control') %>
</article>
<article>
<%= hidden_field_tag(:stripeToken) %>
</article>
<button id='donateButton' class="btn btn-primary">Donate</button>
<% end %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
key: '<%= Rails.configuration.stripe[:publishable_key] %>',
locale: 'auto',
name: 'Place4Grace',
image: '<%= asset_url "creative/small_logo.jpg" %>',
description: 'Thank you for your Donation!',
token: function(token) {
$('input#stripeToken').val(token.id);
$('form').submit();
}
});
$('#donateButton').on('click', function(e) {
e.preventDefault();
$('#error_explanation').html('');
var amount = $('input#amount').val();
amount = amount.replace(/\$/g, '').replace(/\,/g, '')
amount = parseFloat(amount);
if (isNaN(amount)) {
$('#error_explanation').html('<p>Please enter a valid amount in USD ($).</p>');
}
else if (amount < 5.00) {
$('#error_explanation').html('<p>Donation amount must be at least $5.</p>');
}
else {
amount = amount * 100; // Needs to be an integer!
handler.open({
amount: Math.round(amount)
})
}
});
$(window).on('popstate', function() {
handler.close();
});
</script>
Here is my stripe.rb
Rails.configuration.stripe = {
:publishable_key => 'pk_test...',
:secret_key => 'sk_test...'
}
Stripe.api_key = Rails.configuration.stripe[:secret_key]
routes.rb
resources :charges, only: [:new, :create]
And lastly here is my controller:
class ChargesController < ApplicationController
def new
end
def create
#amount = params[:amount]
#amount = #amount.gsub('$', '').gsub(',', '')
begin
#amount = Float(#amount).round(2)
rescue
flash[:error] = 'Charge not completed. Please enter a valid amount in USD ($).'
redirect_to root_path
return
end
#amount = (#amount * 100).to_i # Must be an integer!
if #amount < 500
flash[:error] = 'Charge not completed. Donation amount must be at least $5.'
redirect_to root_path
return
end
Stripe::Charge.create(
:amount => #amount,
:currency => 'usd',
:source => params[:stripeToken],
:description => 'Custom donation'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to root_path
end
end
UPDATE
Here is my route.rb:
Rails.application.routes.draw do
get 'dashboard/index'
get 'dashboard/new'
get 'dashboard/create'
get 'dashboard/show'
get 'dashboard/destroy'
get 'contacts/index'
get 'document/download'
get 'confirmation/confirmation'
get 'document/download'
root 'creatives#index'
get 'access/menu'
get 'access/login'
post 'access/attempt_login'
get 'access/logout'
get 'sessions/index'
get 'sessions/logout'
get 'sessions/profile'
get 'sessions/login'
get 'administrators/index'
get 'administrators/new'
resources :users do
member do
get :delete
end
end
resources :contacts do
member do
get :delete
end
end
resources :charges, only: [:new, :create]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
Update 2
Update 3
I don't know how to fix this or if this even matters but when you create a controller using rails in the terminal it creates a view automatically. I created a charges controller but the charges form is located in the creatives view not the charges view because it is a partial see image the page is donation.html.erb.
I'm trying to set up the Mandrill API to send an email when a user clicks a button, but I cannot seem to get it to send. The email will send perfectly fine from the console, so I know it is not a problem with the template (Devise emails also send find).
I think it is to do with how I have set it up in the controller but I cannot find any help on where I should put it instead.
Here is the code from the controller:
def attending
#event = Event.find(params[:id])
type = params[:type]
if type == "attending" && #event.space != 0
current_user.attending << #event
#event.space = #event.space - 1
#event.save
AdminMailer.new_attending(#event.user, current_user)
redirect_to :back, notice: "You've joined the group. Your number will be sent to #{#event.user.name}"
else type == "unattending"
current_user.attending.delete(#event)
redirect_to :back, notice: "You've removed yourself from the group"
end
end
Here is the admin_mailer.rb
class AdminMailer < ActionMailer::Base
require 'mandrill'
def mandrill_client
#mandrill_client ||= Mandrill::API.new MANDRILL_API_KEY
end
def new_attending(creator, user)
template_name = "new-attending"
template_content = []
message = {
to: [{email: creator.email, name: creator.name}],
subject: "Someone wants to go riding with you!",
merge_vars: [
{rcpt: creator.email,
vars: [
{name: "CREATOR_NAME", content: creator.name},
{name: "USER_NAME", content: user.name},
{name: "USER_NUMBER", content: user.number}
]}
]
}
mandrill_client.messages.send_template template_name, template_content, message
end
end
And here is the link they click in the view.html.erb that should send the email:
<td><% if event.user != current_user && event.space != 0 && user_signed_in? %>
<% unless event.attendees.include?(current_user) %>
<%= link_to "Join", attending_event_path(event, type: "attending"), class: "btn btn-primary btn-xs", method: :put %>
<% end %>
<% end %></td>
Any help in figuring out why it's not sending would be great! As I said, it works in the console when I type:
AdminMailer.new_attending(#event, #user)
Please replace following code.
AdminMailer.new_attending(#event.user, current_user)
with
AdminMailer.new_attending(#event.user, current_user).deliver
I hope this will work.
I'm using Rails3 to build a simple customer information page (in table format). On this page user can edit each customer's detailed information. It's possible for each customer to have multiple records. I use link_to to get to the edit page:
<td class="edit" id="edit">edit
<%= link_to 'edit', :action => :edit, :cust_id => ci.cust_id %>
</td>
edit.html.erb:
<h1>Editing cust</h1>
<%= form_for(#cust_info) do |cust| %>
Customer: <%= cust.text_field :cust_schema %>
<%= cust.submit "Save" %>
<% end%>
In my controller, I have this:
def edit
cust_id = params[:cust_id]
#cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
end
The customer info page shows right. When I click the edit link, I got the error message:
ActionView::Template::Error (undefined method `cust_info_cust_info_path' for #<#<Class:0x7fb0857ce7b8>:0x7fb0857ca780>):
1: <h1>Editing cust</h1>
2:
3: <%= form_for(#cust_info) do |cust| %>
4: Customer: <%= cust.text_field :cust_schema %>
5: <%= cust.submit "Save" %>
6: <% end%>
app/views/track/edit.html.erb:3:in `_app_views_track_edit_html_erb___102324197_70198065248580_0'
Where does `cust_info_cust_info_path' come from?
EDIT: here is the code in the controller:
class TrackController < ApplicationController
def display
end
def information
end
def customerinfo
#cust_info = CustInfo.find(:all, :order=>"cust_id")
#cust_info.each do |ci|
if ci.upload_freq == 'W'
ci.upload_freq = 'Weekly'
elsif ci.upload_freq == 'M'
ci.upload_freq = 'Monthly'
end
end
end
def edit
cust_id = params[:cust_id]
#cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
end
end
end
Change #cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
to
#cust_info = CustInfo.find(cust_id)
I'm looking for a way to use something similar to link_to_unless_current but for sub URLs, so for instance for both these URLs:
/entity_name/
/entity_name/123
it will not result as a link. How can I achieve that in Rails?
UPD: Resolved it my own custom way, please Ruby savvy let me know if it's good.
module ApplicationHelper
def link_to_unless_current_or_sub(name, options = {}, html_options = {}, &block)
link_to_unless current_page_or_sub?(options), name, options, html_options, &block
end
private
def current_page_or_sub?(options)
url_string = CGI.unescapeHTML(url_for(options))
request = #controller.request
if url_string.index("?")
request_uri = request.request_uri
else
request_uri = request.request_uri.split('?').first
end
request_uri.starts_with?(url_string)
end
end
Usage:
<%= link_to_unless_current_or_sub("Users", users_path) %>
i don't think such helper method exist
you have to write something like following
<% if params[:id] %>
"Home"
<% else %>
<%= link_to "Home", { :action => "index" }) %>
<% end %>
Works in Rails 3.2 with some minor adjustments
def current_page_or_sub?(options)
url_string = CGI.unescapeHTML(url_for(options))
if url_string.index("?")
request_url = request.fullpath
else
request_url = request.fullpath.split('?').first
end
request_url.starts_with?(url_string)
end