Link_to target '_blank' combined with controller action - ruby-on-rails

I have the code:
= link_to image_tag(image_info), 'web-site', :target=>'blank'
which works great to open the site in a new tab BUT -
The image is an advertisement that I am hosting and I want to also record the fact that the image was clicked and time and other details.
Is there a way to combine the link_to, target '_blank' with a call to a controller action?

You can achieve that with Javascript and to record the click time you need to define an action which will save the time and other details.
= link_to image_tag(image_info), 'web-site', class: 'save-time'
JS:
$('.save-time').on('click', function(e){
e.preventDefault();
var linkUrl = $(this).attr('href');
$.ajax({
url: '',
type: 'POST'
success: function(response){
if(response){
window.open(linkUrl, '_blank');
}
}
})
});
Hope that helps!

One non-Javascript way of going about this would be to create a controller action that:
Does whatever tracking you want to do
redirects to your external website.
Then set your link up so that it calls your controller action directly.
As a very simple example, that would benefit from a bit more sophistication:
Route
# config/routes.rb
# [...]
get 'tracking/:url_id', to: 'tracking#redirection', as: 'track_redirection'
Controller
# app/controllers/tracking_controller.rb
class TrackingController
def redirection
url = {
1 => 'google.com',
2 => 'bbc.com'
}[params[:url_id]]
TrackingClass.new(url, current_user).track
redirect_to url
end
end
View
= link_to image_tag(image_info), track_redirection_path(1), target: 'blank'
This will create an internal link to /tracking/1 which your controller will then redirect to the correct url.

You can link to the controller method path
link_to "controller/method", target: 'blank', method: :post do
image_tag image_path("whatsapp-icon.svg")
end
Routes
# config/routes.rb
resources :controller do
post "method" => "controller#method"
end

Related

How to execute ruby function with attributes using AJAX request in Rails 6.1?

I have the following home controller:
class HomeController < ApplicationController
def index
#data = EmergencyFriend.all
#jsonData = JSON.pretty_generate(#data.as_json)
end
def about
end
def alertEmergencyContant
account_sid = "my id"
auth_token = "my token"
#client = Twilio::REST::Client.new(account_sid, auth_token)
#client.messages.create(
to: "+number 1",
from: "+number 2",
body: "hello world !"
)
end
end
Basically, in my home/index.html.erb there is only one button. When the button is pressed it shows an alert message that allows user to select an option to send an SMS to.
What I want to do is to call the alertEmergencyContant method in my home controller so that I can send the message. I also want to pass the phone_number as a parameter with that request. It has been suggested that for this I should use AJAX. I successfully installed jquery and ajax in my rails project and works as expected. What I can't understand is how to create it as a POST request.
My routes list for the home directory are :
root GET / home#index
root GET /home/about(.:format) home#about
But there is nothing on alertEmergencyContant. How to declare that in the routes and make it as a POST request? How to pass attributes from JavaScript to ruby using AJAX?
Here is my ajax request so far (This works):
$.ajax({
url: '/',
type: 'GET',
success: function(event){
alert("sending Message");
}
});
UPDATE:
def about
#thisNumber = params[:phone_number]
puts "helllloooooooooooooo " + #thisNumber
end
function ajaxRequest(){
$.ajax({
url: 'home/about/?phone_number:1244211',
type: 'GET',
success: function(event){
alert("passed");
},
failed: function(){
alert("has failed")
},
done: function(){
alert("after")
}
});
}
You need to add a route to your action
# routes.rb
post 'some_url' => 'home#alert_emergency_contact'
You can now use this in your javascript
$.ajax({
url: '/some_url', // This needs to match what you choose in routes.rb
type: 'POST',
success: function(event){
alert("sending Message");
}
});
PS: Action names are always_snake_case in Ruby, not camelCase

Rails form_for only change controller

I would like to tell form_for to use a different controller without affecting the action.
I know how to change the URL like
form_for #car, url: { controller: 'admin/cars' }
but this will also change the action.
Is there any way I can use a different controller with form_for without affecting the automatic choosing of the action?
You can also specify the action like this and could pass the controller name as a variable:
form_for #car, url: { controller: #controller_name, action: "your_action" }
You can also select action in routes, maybe this is helpful for you;
form_for #car, url: { cars_path }
in your routes file ;
post '/cars', to: 'cars#action_whatever_you_want'

Call a method from a form - rails

I have a form to upload a file. I want to call a particular method in my controller when I press my submit button. This is probably a really simple thing but I'm really new to rails.
I have a method in my videos_controller called "upload_translation_handwritten"
Here is my form:
%form{role: 'form'}
.form-group
%label.h4{for: "handwrittenTranslation"} Upload Handwritten Translation
%input#inputFile{name: 'translation', type: "file"}
%button.btn.btn-default{type: "submit"} Upload
I have a route:
match 'users/:id/videos/:video_id/translate_video_handwritten' => 'videos#upload_translation_handwritten', via: 'post', as: :upload_translation_handwritten
I'm already at 'users/:id/videos/:video_id/translate_video_handwritten' and I want to call this other method that does a couple things then redirects to the same page with a little flash message. Right now, when I click "upload", nothing happens :(
Thanks in advance!
rails convention
check form action(routing) and method(post)
<form action="this" method="and this">...</form>
in routes.rb
match "**/videos/:video_id" => "vidoes#edit", :as => :get # upload form as html
match "**/videos/:video_id/upload" => "videos#upload", :as => :post # upload and redirect with flash
in videos_controller.rb
def upload
...
flash[:msg] = "Not suppported video format"
render "edit"
end
in upload_form.html.haml
- if flash[:msg]?
= flash[:msg]
You need to add url for attribute action. In your case, I think it is %form{role: 'form', action: upload_translation_handwritten_user_video_path(user_id, video_id), method: :post}. Please run rake routes to see right named helper
Your route points out to the POST method only,
You have to accept it for GET method also.
Change your route to
match 'users/:id/videos/:video_id/translate_video_handwritten' => 'videos#upload_translation_handwritten', as: :upload_translation_handwritten
Then You can able to view your Form, No need to give action in your form,
After Update Your Controller like this
def upload_translation_handwritten
# Perform Your actions for both GET and POST
# check with
if request.post?
# Add codes for actions after submission of form
else
# render your form
end
end
I ended up fixing it by changing:
%form{role: 'form'}
TO
=form_tag(:action => 'upload_translation_handwritten', :method => 'post')
Thank you everyone for your help!!

Routing in Ajax petition in Rails 2

I have the following in my view:
$('#anID tr').click(function () {
$.ajax({
type: 'GET',
url: '/tickets/extended_info',
dataType: 'script',
data: { id: $(this).find('td:first').html() }
});
});
and this in my tickets controller:
def extended_info(id)
puts ">>>>>>>>>>>>>>> " + id.to_s
end
But I always get 404 not found from the ajax request.
I think I'm missing something in my routes file... I tried several things, but nothing.
Any ideas?
>>>>>>>>>>>>>>>>>>>>> RESOLVED <<<<<<<<<<<<<<<<<<<<<<<<<
I had to add:
map.extendedInfo '/extended_info/:id', :controller => 'tickets', :action => 'extended_info'
to my routes file.
Also, I was using "GET" in my ajax call in my JavaScript ... I changed to POST and now it's working =)
Really seems like routing trouble. Do you have appropriate row for /tickets/extended_info path in your routes.rb? If so, can you post it here?
I suppose something like this
get "/ticket/extended_info", :to => "tickets_controller#extended_info"
in routes.rb and your action on controller should be just
def extended_info
puts params[:id].inspect
end

Ruby/Rails/AJAX/JQuery - On link click, passing a parameter and performing a controller action

I'm trying to use clicking a link to perform and action in my controller called 'yes' but do so client side rather than having to refresh everytime a user clicks.
Before I had an link_to that routed to a action called "yes" and passed the id of a model I have called 'event'
<%= link_to "yes", yes_path(event)%> (in view)
match 'user/:id/yes' => 'user#yes', :as => "yes" {in routes.rb)
The problem issue is that every time the user clicks the link the page refreshes while it performs the yes action, so it will flow alot smoother if I can tell the backend to perform the actions client side.
S0 I found a reference here : execute controller/action from javascript in rails3
and took a look at the documentation : http://api.jquery.com/jQuery.ajax/
And came up with this. Where if the post is successful at the previous route from above change a css class for the link (change color).
$.ajax({
type: "POST",
url: "/user/" + $(this).attr('event') + "/yes/",
success: function(){
$(".like").click(function() {
if ($(this).hasClass("selected")) {
$(this).addClass("selected");
return false; }
});
I also added this is the bottom of the controller that the desired javascript is being used.
respond_to do |format|
format.html { }
format.js
end
So now my link_to looks like this
<%= link_to "yes", yes_path(event), :class => "like", :remote => true %>
But the page is still refreshing and It doesnt look like its calling the AJAX at all.
am I passing the parameter "event" properly as a jquery attribute?
am I calling the link_to properly?
This is my first time so I have no idea what I'm doing wrong, possibly a few things?
I'd really appreciate any help
Is this what you're after?
$(".like").click(function(evt) {
evt.preventDefault();
var $self = $(this);
$.post($self.attr("href"), function(response) {
$self.addClass("selected");
});
});
The first line binds the JavaScript to all elements with a class of like. preventDefault is the preferred way to prevent the default behavior of an anchor tag (navigate to the href). $.post() is shorthand for $.ajax({ type: "POST" }).
Whatever you want to happen after a successful post to the server goes that finally function call. The first argument is the response from the server.
Rich

Resources