Here are two routes
Route::group(['prefix' => 'admin', 'middleware' => ['role:superAdmin']], function() {
Route::get('/dashboard', 'Admin\AdminController#getDashboard');
});
Route::group(['prefix' => 'user', 'middleware' => ['role:user']], function() {
Route::get('/profile', 'User\UserController#getProfile');
});
If user try to access /admin/dashboard Not authorized view should be show.
You can intercept Exceptions in Laravel and do whatever you want to do with them. In this case you can catch the HTTP exception and then show a view or controller.
Check out the render() method here https://laravel.com/docs/5.1/errors#the-exception-handler
Related
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
I am suffering this issue since the beginning of my website development. I am using rails as the backend framework. When I refresh any page, I am navigated to the index page.
For ex: if I am on www.google.com/ab/xyz/123 and I refresh, then I am navigated to www.google.com.
I am providing my angular and rails code with parameters changed due to my company's policy.
Angular routing
angular.module('SampleApp').config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('page1', {
url: '/page1',
templateUrl: "<%= asset_path('page1.html') %>"
})
.state('page2', {
url: '/page2',
templateUrl: "<%= asset_path('page2.html') %>"
})
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
}
]);
Rails routing
scope '/google' do
get '/page1' => 'controller#get_page1', :constraints => { :format => 'html' }
get '/page2' => 'controller#get_page2', :constraints => { :format => 'html' }
the below matches for the unknown urls
match '/*path' => redirect('/google.com'), via: :all
I would appreciate if anyone could take out some time out of you busy schedule and let me know the solution.
Thanks in advance.
scope '/google' means that the URLs to page1 and page2 will be /google/page1 and /google/page2 respectively.
I am assuming that the line match '/*path' => redirect('/google.com'), via: :all is out of the scope '/google'.
Now, as per your statement, if you're on a URL such as www.google.com/ab/xyz/123 and refresh the page, you get redirected to www.google.com. This is the right scenario. Since your rails app doesn't support any such routes, it will match the other path and will redirect to google.com.
Why angular works? Angular router doesn't consult with Rails before routing. It just follows what you've defined as your states. That's why the URLs such as /page1 and /page2 will work on Angular side. But as soon as you refresh your page, the control goes back Rails, and since Rails doesn't know what that route is, it will redirect you.
In Rails 4, I've got several different domain names pointing to same app.
I want root to be able to redirect to registration action with different parameters depending on the url
Below is what I have but it's not working so far.
get "/" => "registrations#new",
:constraints => { :domain => "domain.com.au" },
:defaults => { :id => '3' }
Is there a way to get this working so it automatically goes to registrations controller new action with id of 3 for domain.com.au only?
I'm trying to implement something similar to http://pusher-chat.heroku.com/
However, I cannot figure out how to call an action without the page refreshing.
The page refreshing defeats the purpose of using pusher.
So far I have created a chat table, with attributes account_id and message.
In my chat controller I have the following:
def create
account = Account.getAccountById(session[:user])
if params[:message].blank?
#title = "Chat"
#chatLog = Chat.find(
:all,
:order => "created_at ASC",
:limit => 20
)
render :action => :index
else
chatter = Chat.new(
:account_id => account.id,
:message => params[:message]
)
payload = {
"account_id" => chatter.account_id,
"message" => chatter.message
}
if chatter.save
Pusher['chat-channel'].trigger('send_message', payload)
#title = "Chat"
#chatLog = Chat.find(
:all,
:order => "created_at ASC",
:limit => 20
)
render :action => :index
else
render :action => :index
end
end
rescue ActiveRecord::RecordNotFound
reset_session
redirect_to(new_account_path)
end
In my chat.js file I have the following:
$(document).ready(function() {
// Enable pusher logging - don't include this in production
Pusher.log = function(message) {
if (window.console && window.console.log) window.console.log(message);
};
// Flash fallback logging - don't include this in production
WEB_SOCKET_DEBUG = true;
var pusher = new Pusher('62651eca256339fa7fca');
var channel = pusher.subscribe('chat-channel');
channel.bind('send_message', function(chatter) {
$('#loading').show();
});
});
I've never built anything like this before, so I would appreciate any help.
I know there has to be a lot more javascript involved.
Thank you,
Brian
To call an action without refreshing you should use ajax.
I haven't tried pusher yet but it seems that whenever someone "submits" a new message, your application, it shall send to the pusher channel so it can broadcast to every "subscribed" client online.
If this is correct, you should think the whole thing as this:
When someone clicks on "new chat" it will create a new chat room, instantiate a new channel on pusher and save it on database. This will generate the identification on the url, that you can send to someone so that they can join your chat.
On the chat screen, you will have one big div that will render the chat and on input text field where you send messages. This particular field will submit to your application using ajax your chat ID and the message.
On your chat controller when you receive this information, you go get the pusher channel id on database for that chat room, save message on database for history and send it back to every user connected on that room with pusher.
The logic to render the text on the chat will be done by client side javascript.
Hmmh, my approach would be to use a Javascript timer which calls an AJAX-script every two seconds to get the new chat entries since the last request - and then refresh only the chatbox. Like so:
var latest_entry_number = 0;
var chatter = window.setInterval("getNewestEntries()",2000);
function getNewestEntries() {
$.ajax({
url: "/path/to/latest_entries",
type: "POST",
dataType: "JSON",
data: {latest_entry: latest_entry_number}
success: appendEntries
});
}
function appendEntries(data) {
latest_entry_number = data.latest_entry;
$.each(data.entries, function(key,val){
//append the entries to the chat
})
}
And the controller action would look like this:
def latest_entries
data[:latest_entry] = get_latest_entry # each entry gets a consecutive, ascending number
data[:entries] = get_entries_since(params[:latest_entry_number]) # get all entries done since that number
# Should be an array
render :json => data
end
Or something like that.
With both views and panels (via the page manager), you can create a page that accepts arguments like users/%/points.
However, I don't need any of the other functionality of these modules beyond the creation of that dynamic page URL. I simply want to create a page that will appear when someone is at the url users/%/points. How can I set up a URL like that without using a module like Views or Panels?
Drupal has a system to create dynamic pages, this is what happens when you view a node or a user. You got a few options, but it all happens in hook_menu.
function modulename_menu() {
$items = array();
$items['users/%user/points'] = array(
'page callback' => callback, // the function to call
'page arguments' => array(1), // The argument to pass, 1 = %user, which will be a user object.
...
);
$items['users/%/points'] = array(...);
$items['users/points'] = array(...);
}
In the first example, you utilize Drupal's load system. Drupal will call user_load on the argument index at 1, if it finds a user, that will be available instead of the actual argument (the user id). If no user is found 404 will be returned.
In the second example, any argument is allowed, which means that you would get a page if you tried to access user/my-little-pony/points.
In the third example is used to show that Drupal allow additional args. So if you want to access user/points/pony, you would get the user/points page with additional args which could be used, if your callback function allows it.
Remember to set some sort of access control as well. You can define custom functions to determine if the user should have access, you use the drupal menu system and require permissions, like access content.
Ready made code:
/**
* Implementation of hook_menu().
*/
function example_menu() {
$items = array();
$items['user/%/points'] = array(
'title' => 'Page title here',
'description' => 'Description here, mostly used for admin pages',
'page callback' => 'example_callback',
'page arguments' => array(1)
'access arguments' => array('access content'),
);
return $items;
}
example_callback($arg) {
return t('The arg is #arg', array('#arg' => $arg));
}
This would need to go into example.module and you would need to create an example.info file. You could change example into whatever module you have created.
If I understand you correctly, it can be done quite easily with hook_menu inside a custom module. Here is example for dynamic page with dynamic title created with variable that the user inserts.
function MYMODULE_menu() {
$items = array();
$items['user/points/%/'] = array(
'page callback' => 'MY_PAGE_CALLBACK_FUNCTION',
'title callback' => 'MY_PAGE_CALLBACK_TITLE_FUNCTION',
'title arguments' => array(3),
'type' => MENU_CALLBACK,
);
return $items;
}
function MY_PAGE_CALLBACK_TITLE_FUNCTION($arg) {
return "My dynamic title: " . $arg;
}