Monthly Archives: March 2012

POST http://192.168.1.3:3000 406 (Not Acceptable) – AJAX with Ruby on Rails

Just a quick post on an error I ran into today when trying to create an AJAX image upload with Ruby on Rails. When submitting an AJAX form I received the following error:

POST http://192.168.1.3:3000/uploads 406 (Not Acceptable)

It turns out that there is a fairly simple (and admittedly obvious) solution. Ensure that your controller has an appropriate response for JavaScript files:

i.e.
Form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%= form_for(@upload, :html =>{:multipart => true}, :remote => 'true') do |f| %>
  <% if @upload.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@upload.errors.count, "error") %> prohibited this image from being saved:</h2>
      <% @upload.errors.keys.each do |field| %>
        <% @upload.errors[field].each do |msg| %>
          <% if field.to_s == "uploads.upload_content_type" %>
            <li><%= field.to_s + " " + msg %></li>
        <% end %>
      <% end %>
    </div>
  <% end %>
  <div>
    <p>
      <%= f.file_field :upload %>
    </p>
  </div>
  <div class="actions">
    <%= f.submit :class => 'button' %>
  </div>
  <%= f.hidden_field :product_id, :value => @upload.product_id %>
<% end %>

Form JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* Wait for document to load */
$(document).ready(function() {
    create_ajax_form('new_upload');
})
 
/* Create an ajax form */
function create_ajax_form(form_id){
 
   //Handle ajax submission
   $j('#' + form_id).submit(function(){
 
       //Send for data
       $j.post($j(this).attr("action"), $j(this).serialize(), null, "script");
 
       //Return false
       return false;
   });
}

Controller Action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#Create an upload
  def create
 
    #Create vars
    @upload = Upload.new(params[:upload])
 
    #Create responses
    respond_to do |format|
      if @upload.save
 
        #Retrieve product
        @product = Product.find_by_id(@upload.product_id)
 
        #Create success responses
        format.html { redirect_to @product, :notice => 'Image Added Successfully!'}
        format.js
      else
 
        #Create error responses
        format.html { render :action => 'new'}
        format.js
      end
    end
  end

JavaScript Response:

1
alert('test');

Modal Popup – Twitter Bootstrap

Just a quick post on how to create a modal popup using twitter bootstrap:

Step #1:

Add the following to a page element such as a link or button in order to open the modal:

     href="modal_content_name"
     data-toggle="modal"

i.e.

<a type="button" class="btn" style="width:100%;" href="#test_modal" data-toggle="modal">Add Image</a>

Step #2:
Create a content div i.e.

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="modal fade" id="test_modal">
  <div class="modal-header">
    <a class="close" data-dismiss="modal">&times;</a>
    <h3>Modal Header</h3>
  </div>
  <div class="modal-body">
    <p>Test Modal</p>
  </div>
  <div class="modal-footer">
    <a href="#" class="btn" data-dismiss="modal">Close</a>
    <a href="#" class="btn btn-primary">Save Changes</a>
  </div>
</div>

And that’s all there is to it, just make sure you’ve included the bootstrap-modal.js file.

Modal Popup - Twitter Bootstrap

Modal Popup - Twitter Bootstrap


Open Twitter Bootstrap Modal Popup on Page Load:
In order to open the modal dialog on page load simply add the following JavaScript:

1
2
3
4
5
<script type="text/javascript">
    $(document).ready(function(){
        $('#test_modal').modal('show');
    });
</script>

You can also close the modal popup manually by using the following JavaScript:

1
2
3
<script type="text/javascript">
$('#test_modal').modal('hide')
</script>

Adjust Modal Width:
In order to adjust the modal width you have two options, Javascript or CSS. You can use the following JavaScript mentioned on GitHub:

1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript">
   $('#test_modal').modal({
        backdrop: true,
        keyboard: true,
        show: false \\remove this if you don't want it to show straight away
    }).css({
        width: 'auto',
        'margin-left': function () {
            return -($(this).width() / 2);
        }
    });
</script>

Or this CSS from StackOverflow:

1
2
3
4
5
6
body .modal-admin {
    //new custom width
    width: 750px;
    //must be half of the width, minus scrollbar on the left (30px)
    margin: -345px 0 0 -375px;
}

Show modal when the user scrolls past certain div
I’ve received another request on how to show the modal when a user scrolls to a certain div. The following should work, but please let me know if you have any issues.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* Wait for document to load */
$(document).ready(function(){
 
$(window).scroll(function(){
 
//Retrieve scroll distance from top
var top = $(window).scrollTop();
 
//Retrieve the divs distance from top of page
var div_distance = $('my_div').offset().top;
 
//Use this if you want a bit of a variable distance, for instance if they scroll 150 pixels past the div
var buffer_distance = 150;
 
//Check if scrolled past div
if(top >= div_distance && top <= (div_distance + buffer_distance)){
 
//Show modal - you may want to add checks etc to see if it's already show
$('#test_modal').modal('show');
 
} else {
 
//Hide the modal, have scrolled past - you may want to add some checks to see if it's already hidden etc
$('#test_modal').modal('hide');                         
}        
}); 
});

Unique Values – Ruby on Rails

Just a quick post on how to select unique values in rails using the uniq operator:

1
2
3
4
5
6
7
8
9
10
11
#All recent categories
<% recent_categories = Category.joins(:products).where('products.user_id = ?', current_user.id).order('products.created_at desc') %>
 
#Results
Cars
Trucks
Cars
Technology
Phones
Technology
...
1
2
3
4
5
6
7
8
#Unique recent categories
<% recent_categories = Category.joins(:products).where('products.user_id = ?', current_user.id).order('products.created_at desc').uniq %>
 
Cars
Trucks
Technology
Phones
...

Popover Function – Twitter Bootstrap

Just a quick post on how easy it is to implement a popover with twitter bootsrap:

JavaScript:

//Create tooltips for login/signup forms
function create_tooltips(){
 
    //Create vars
    var titles = ['test title']
    var contents = ['test content'];
    var fields = ['#user_email'];
 
    //Loop through each field and assign tooltip
    for(var i = 0; i < fields.length; i++){
 
        //Create vars
        var field = $(fields[i]);
        var title = titles[i];
        var content = contents[i];
 
        //Ensure field found
        if(field){
 
            //Create popover
            $(field).popover(
                {
                    animation: true,
                    placement: 'right',
                    selector: false,
                    trigger: 'hover',
                    title: title,
                    content: content,
                    delay: 0
                });
        }
    }
}

Form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  <div class="span4">
    <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :class => 'form-vertical') do |f| %>
    <fieldset class="well">
      <div class="control-group">
        <%= f.label :email, 'Email:' %>
        <div class="controls">
          <%= f.email_field :email %>
        </div>
      </div>
      <div class="control-group">
        <%= f.label :display_name, 'Display Name:' %>
        <div class="controls">
          <%= f.text_field :display_name %>
        </div>
      </div>
      <div class="control-group">
        <%= f.label :password, 'Password:' %>
        <div class="controls">
          <%= f.password_field :password %>
        </div>
      </div>
      <div class="control-group">
        <%= f.label :password_confirmation, 'Password Confirmation:'%>
        <div class="controls">
          <%= f.password_field :password_confirmation %>
        </div>
      </div>
      <div class="control-group">
        <%= f.submit "Sign up", :class => 'btn btn-success' %>
      </div>
    </fieldset>
    <% end %>
  </div>

Result:

Popover - Twitter Bootstrap

Popover - Twitter Bootstrap

That’s all there is to it, if you haven’t had a chance to check it out yet make sure you head on over to the official site – there are some pretty neat features.

Allow HTML String – Ruby on Rails

Just a quick post on how to prevent escaping for HTML within a string. Simply use html_safe?.

i.e. The following will show the bold tags as text:

<%= "<b>GOOOOOOOGLE</b>">

<b>GOOOOOOOGLE</b>

Whereas once we add html_safe the text will be displayed in bold:

<%= ("<b>GOOOOOOOGLE</b>").html_safe?>

GOOOOOOOGLE

Unable to Login to AppDesigner – PeopleSoft

I couldn’t login to Application Designer today for some reason. I kept getting an “Invalid User ID and password for signon.” error despite my credentials being correct.

Invalid User ID and password for signon.

Invalid User ID and password for signon.

It turned out that adding the EOPP_USER and PAPP_USER roles fixed the issue:

1: Navigate to the user’s profile (PeopleTools > Security > User Profiles > User Profiles)
2: Enter the user’s ID and press search
3: Select “Roles” from the top row of tabs
4: Add the “EOPP_USER” and “PAPP_USER” roles
5: Press save

EOPP_USER and PAPP_USER Roles - PeopleSoft

EOPP_USER and PAPP_USER Roles - PeopleSoft

Access Log – PeopleSoft

I came across a requirement today where I needed to find out when a user had last logged into PeopleSoft. The record PSACCESSLOG came in handy here, it stores all of the following:

PSACCESSLOG
OPRID: The users operator ID
LOGIPADDRESS: The users IP address
LOGINDTTM: A timestamp showing when the user logged in
LOGOUTDTTM: A timestamp showing when the user logged out
PT_SIGNON_TYPE: The signon type

Find Last Login Date for User:

SELECT *
FROM PSACCESSLOG
WHERE oprid = '<OPERATOR ID>'
ORDER BY effdt DESC;

Find all logins since 1st March 2012:

SELECT *
FROM PSACCESSLOG
WHERE TO_DATE(CAST(logindttm AS DATE), 'dd/mm/yy') >= TO_DATE('01/03/2012', 'dd/mm/yy');
PSACCESSLOG - Login History in PeopleSoft

PSACCESSLOG - Login History in PeopleSoft

Leave a comment below if you have any questions.