Hopefully this will be a time saver for anyone else who goes through the following pain.
I have a brand spanking new OSX 10.6 installation.
I installed mysql 5.5.9-OSX10.6-X86 (because I thought everything was still i386 based…watch this space!)
I installed RVM and installed ruby 1.92 under RVM control.
I then do a ‘bundle install’ and it gripes about not having mysql2 gem installed. I do a manual install using the following command.
and after a bit of crunching, we get to the following error:
Building native extensions. This could take a while...
ERROR: Error installing mysql2:
ERROR: Failed to build gem native extension.
1.9.1/ruby/ruby.h:108: error: size of array ‘ruby_check_sizeof_long’ is negative
/Users/peter/.rvm/rubies/ruby-1.9.2-p180/include/ruby-1.9.1/ruby/ruby.h:112: error: size of array ‘ruby_check_sizeof_voidp’ is negative
In file included from /Users/peter/.rvm/rubies/ruby-1.9.2-p180/include/ruby-1.9.1/ruby/intern.h:29,
from /Users/peter/.rvm/rubies/ruby-1.9.2-p180/include/ruby-1.9.1/ruby/ruby.h:1327,
from /Users/peter/.rvm/rubies/ruby-1.9.2-p180/include/ruby-1.9.1/ruby.h:32,
from ./mysql2_ext.h:4,
from client.c:1:
/Users/peter/.rvm/rubies/ruby-1.9.2-p180/include/ruby-1.9.1/ruby/st.h:69: error: size of array ‘st_check_for_sizeof_st_index_t’ is negative
The Solution
Uninstall your MySQL using the commands below
sudo rm /usr/local/mysql
sudo rm -rf /usr/local/mysql*
sudo rm -rf /Library/StartupItems/MySQLCOM
sudo rm -rf /Library/PreferencePanes/My*
edit /etc/hostconfig and remove the line MYSQLCOM=-YES-
sudo rm -rf /Library/Receipts/mysql*
sudo rm -rf /Library/Receipts/MySQL*
Now go and download the 64 bit version of the MySQL package – get the dmg rather than the gzip file.
The rationale behind this is that your new beaut 10.6 is actually referencing 64 bit modules by default. How to prove this I do not know – I’m confused and still searching for the answer. If I do a uname – a I get…
Darwin MacBook-Air.local 10.6.0 Darwin Kernel Version 10.6.0: Wed Nov 10 18:13:17 PST 2010; root:xnu-1504.9.26~3/RELEASE_I386 i386
Now, if I’m not mistaken that’s an i386 at the end – go figure. If anyone has any further insights please let me know.
The next step is to download the gem for your ruby/rails use
sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- \
--with-mysql-dir=/usr/local/mysql --with-mysql-lib=/usr/local/mysql/lib \
--with-mysql-include=/usr/local/mysql/include
The next error encountered is when I try to start the rails server using ‘rails s’
/Users/peter/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.6/lib/mysql2.rb:7:in `require': dlopen(/Users/peter/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.16.dylib (LoadError)
The answer to this problem is to run the following command…
sudo install_name_tool -change libmysqlclient.16.dylib /usr/local/mysql/lib/libmysqlclient.16.dylib ~/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle/
Bear in mind, I’m running version 1.9.2-p180 fo ruby – you will need to change the command for whatever version you’re running.
2 Comments // Posted on 15 March, 2011 // GNU/Linux, OSX, Ruby on Rails, Uncategorized
I’ve just upgraded to Rails 3 and hit a real blocker that’s taken me two days to work out. I hope this post can save someone else even a few hours of stuffing around with Rails 3, jQuery, unobtrusive javascript and other assorted gems.
The problem
I have a user profile form with dropdown selects for country, region and city. To start out, only the country select is populated. When the user selects a country, the region select populates with regions from that country, when a region (aka state/territory) is selected, the city list is populated. I know there are countries that don’t have regions, but that’s another day’s thinking.
My setup is fairly simple. I’m using jQuery, NOT prototype, so there’s no observe_field. Try to use such will result in an error ‘observer_field undefined method’. I’m using formtastic as a UI helper because I’ve been impressed by it’s DRYness and I’m tired of coding html forms. This solution shows the formtastic layouts, but can be applied to standard rails forms very easilyy.
jQuery setup
I’m using the jQuery 1.4.2 minimized version of the file from Google and a jquery/ujs wrapper/helper file I downloaded from github at http://github.com/rails/jquery-ujs/blob/master/src/rails.js.
I renamed this file as rails.jquery.js and copied it to the folder public/javascripts/ under the root of my application folder.
Next step is to update the javascript files that are included in the header of your application. So, open up app/views/layouts/application.html.erb
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "rails.jquery.js", "application.js" %>
<%= csrf_meta_tag %>
The javascript_include tag lists specifically those files I need. If you use the “defaults” option you’ll end up with the prototype.js included in the mix. This is something I’m trying to avoid given it’s not UJS.
The csrf_meta_tag reference is a Rails 3 enhancement. It seeks to avoid cross site scripting issues by ensuring the token created by the authenticated visitor is maintained throughout the site, thereby ensuring that a button click or post back has actually come from a genuine session.
Update routes.rb
When a change of a select list is triggerd, an Ajax post will be made to my profiles controller (remember we’re dealing with the ‘profile’ model here). I’m using two actions, update_state_select and update_city_select.
To add these calls into the routes.rb file, update it with the following:
resources :profiles
match 'profiles/update_state_select/:id', :controller=>'profiles', :action => 'update_state_select'
match 'profiles/update_city_select/:id', :controller=>'profiles', :action => 'update_city_select'
The main form
The form where users can enter their new profile details is called new.html.erb and resides under the app/views/profiles folder. It’s a formtastic form, but once you’ve seen the code, you can do the mental shift to whatever other UI component you fancy.
<% semantic_form_for @profile, :remote=>true, do |form| %>
<% form.inputs do %>
<%= form.input :firstname %>
<%= form.input :middlename %>
<%= form.input :lastname %>
<%= form.input :image, :as=> :file %>
<%= form.input :timezone_adjustment, :as=> :time_zone %>
<%= form.input :gender, :as => :radio, :label => "Gender", :collection => [["Male", "M"], ["Female", "F"]] %>
<%= form.input :birthday, :as=> :date, :start_year =>1930 %>
<%= form.input :facebook_profile_url %>
<%= form.input :linkedin_profile_url %>
<%= form.input :country_id, :collection=>Country.find(:all, :order=>:name).collect{ |c| [c.name,c.id]}, :required=>true %>
<div id="addressStates">
<%= render :partial => 'states' %>
</div>
<div id="addressCities">
<%= render :partial => 'cities' %>
</div>
<%= form.buttons :commit %>
<% end %>
<% end %>
Handle the change events
We have to add in the javascript now that will get fired when the first select (the country list) is changed. This is a piece of javascript code I’ve decided to put into the application.js file under the public/javascripts file.
The code looks like this:
jQuery(function($) {
// when the #country field changes
$("#profile_country_id").change(function() {
// make a POST call and replace the content
var country = $('select#profile_country_id :selected').val();
if(country == "") country="0";
jQuery.get('/profiles/update_state_select/' + country, function(data){
$("#addressStates").html(data);
})
return false;
});
})
What’s happening here is the jQuery code is waiting for a change to be triggered by a control called ‘profile_country_id’. When a change is detected, it’s taking the value of the selected value and passing it as a parameter to the get call on profiles/update_state_select. The results of the call will end up being rendered as html in the addressStates div.
If you have firebug installed (and you should!!) you can see the javascript get being triggered in the console window. If you haven’t implemented the update_state_select method in your controller, you’ll probably get a 404 error.
The controller
This is the simple bit apart from a few minor tweaks to accommodate Rails 3 ActiveRecord queries
def update_state_select
states = Region.where(:country_id=>params[:id]).order(:name) unless params[:id].blank?
render :partial => "states", :locals => { :states => states }
end
Note the use of the ‘where’ and the ‘order’ methods applied directly to the entity name. I think this is one of the neatest changes in the Rails 3 ActiveRecord domain. I’m going to have to build an automation utility to update all my old code.
Rendering the partial
In the simplest case, the partial that displays the states should just be a select populated with the results of the update_state_select method call. There’s a ‘but…’ coming up so pay attention.
#This is _states.html.erb stage 1 - without the jQuery code
<%= semantic_form_for "profile", :remote=>true, do |form| %>
<%= form.inputs do %>
<% if !states.blank? %>
<%= form.input :region_id, :collection=>states.collect{ |s| [s.name,s.id]} %>
<% else %>
<%= form.input :region_id, :collection=>[] %>
<% end %>
<% end %>
<% end %>
So far it’s looking good, when a user selects the country drop-down the jQuery event is triggered, that does a Get to the controller. The controller builds a collection and passes it to the _states partial. However, (this is the ‘but’ I mentioned) I couldn’t get the change event of the state drop-down unless I put the jQuery code in as part of the partial. If anyone knows what/how to add this code to the application.js and still get it to fire, please let me know.
To get the change event of the state_id select to trigger, add the following code to the top of the _state.html.erb file. Note how similar it is to the code in the application.js file
<script type="text/javascript">
jQuery(function($) {
// when the #region_id field changes
$("#profile_region_id").change(function() {
// make a POST call and replace the content
var state = $('select#profile_region_id :selected').val();
if(state == "") state="0";
jQuery.get('/profiles/update_city_select/' + state, function(data){
$("#addressCities").html(data);
})
return false;
});
})
</script>
Now we have a functioning form with an Ajax enabled country and state select lists. All that’s left to do is to do a copy and paste of code in the profiles controller to get the update_city_select method working and add a new _cities.html.erb partial to display the results of the controller method call.
Here’s all the relevant code for the controllers/profiles_controller.rb file:
def update_city_select
cities = City.where(:region_id=>params[:id]).order(:name) unless params[:id].blank?
render :partial => "cities", :locals => { :cities => cities }
end
And the code for the app/views/profiles/_cities.html.erb partial:
<%= semantic_form_for "profile", do |form| %>
<%= form.inputs do %>
<% if !cities.blank? %>
<%= form.input :city_id, :collection=>cities.collect{ |c| [c.name,c.id]} %>
<% else %>
<%= form.input :city_id, :collection=>[] %>
<% end %>
<% end %>
<% end %>
Summary
I hit the first wall when I added an observe_field and couldn’t explain why I was getting method undefined errors. That started me down a long and winding road of frustration. I think I’ve overcome most of the frustrations and I’m starting to get the hang of the Rails 3 changes.
There is a plugin that will allow you to keep your old Rails 2 ways alive but every time I saw mention of it, I also saw comments about how bad an idea it is. I mean, you could probably also run some COBOL code as a plugin, but why live in the past?
References
jQuery files from Github
Formtastic plugin
Beware: Use the proper branch for Rails 3 gem ‘formtastic’, :git => “http://github.com/justinfrench/formtastic.git”, :branch => “rails3″
Simone Carletti’s Blog
Ryan Bates’ excellent video cast series
A couple of people asked me to show more info on the actual table design and models used in this example. You can read more on this site by following this link Rails 3, jQuery and multiselect dependencies part 2.
Comments, questions and suggestions welcome
11 Comments // Posted on 13 August, 2010 // Ruby on Rails
I’ve just spent an hour arguing with a new install of ruby 1.92, rails 3.0.2rc and PostgreSQL.
Every time i tried to do a db:migrate I got a strange error.
rake db:migrate
(in /home/peter/projects/workspace/testapp)
rake aborted!
no such file to load -- pg
I did the usual trawling around helpful websites, each suggesting I hadn’t the correct database gem installed. some referred to pg, some to postgresql, other to ruby-postgres.
What I have installed is listed below
abstract (1.0.0)
actionmailer (3.0.0.rc)
actionpack (3.0.0.rc)
activemodel (3.0.0.rc)
activerecord (3.0.0.rc)
activeresource (3.0.0.rc)
activesupport (3.0.0.rc)
arel (0.4.0)
builder (2.1.2)
bundler (1.0.0.rc.2)
capistrano (2.5.19)
erubis (2.6.6)
highline (1.6.1)
i18n (0.4.1)
mail (2.2.5)
mime-types (1.16)
minitest (1.6.0)
net-scp (1.0.2)
net-sftp (2.0.4)
net-ssh (2.0.23)
net-ssh-gateway (1.0.1)
pg (0.9.0)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.9)
rack-test (0.5.4)
rails (3.0.0.rc)
railties (3.0.0.rc)
rake (0.8.7)
rdoc (2.5.8)
sqlite3-ruby (1.3.1)
thor (0.14.0)
treetop (1.4.8)
tzinfo (0.3.22)
The fix for the 'no such file to load — pg' error is to update the new Gemfile file in your application’s root folder.
#Comment out the sqlite3 requirement
#gem 'sqlite3-ruby', :require => 'sqlite3'
#Add a pg requirement
gem 'pg', :require => 'pg'
Once you’ve done this do a bundle install from your application root folder. This ensures you have all required gems installed. Another hour wasted fighting against the machine.
11 Comments // Posted on 2 August, 2010 // Databases, Ruby on Rails
I’ve just posted a little project up to the gitorious website for my and other’s pleasure. The last few freelance projects I’ve worked on have required the functionality to provide users with a way to enter their location using a prompt system by selecting country first, then entering their region/state and finally their town and city. The database structure uses a standard Rails convention and is MySQL based. It can be very easily converted to any other SQL supported format.
Click here to browse to the project.
No Comments // Posted on 28 July, 2010 // Databases, Git, Ruby on Rails
This extract is from notes I took during the process of setting up both a desktop and laptop for general use as a development environment for Ruby on Rails (RoR) and PHP development.
There were lots of other steps (custom gems and environment stuff I like), but most of what follows is generic enough to get the basics in place. Happy Hacking!!
Installing Skype
sudo apt-get install libqt4-dbus libqt4-network libqt4-xml libasound2
sudo dpkg -i skype-ubuntu-intrepid_2.1.0.81-1_amd64.deb
Installing Amarok
sudo apt-get install xine-ui libxine1-ffmpeg
To get remote shares mapping in fstab.
Firstly, install the smb client package
sudo aptitude install smbfs
sudo apt-get install portmap nfs-common
Then add the following line to /etc/hosts.deny:
echo portmap : ALL>>/etc/hosts.deny
By blocking all clients first, only clients in /etc/hosts.allow below will be allowed to access the server.
Now add the following line to /etc/hosts.allow. User your own IP address.
echo portmap : 192.168.0.20>>hosts.allow
Next create the mounting points on your system
sudo mkdir /mnt/<name of mounting point>
sudo mkdir /mnt/music
sudo mkdir /mnt/backups
Create a file in home folder called .smbcredentials (note the leading dot)
touch ~/.smbcredentials
echo username=[your network username] >> ~/.smbcredentials
echo password=[your network password] >> ~/.smbcredentials
chmod 600 ~/.smbcredentials
Now an entry in /etc/fstab using the ip address of your NAS
#Added a permanent share to shares on NAS box
#Note: everything that follows (up to the 0 0 should appear on the one line)
#and one line is required for each share you want to map
//192.168.0.20/<foldername on NAS> /mnt/<local foldername> cifs
uid=peter,credentials=/home/peter/.smbcredentials,domain=office,dir_mode=0777,file_mode=0777 0 0
Now, for a few of the other standard tools
Setup filezilla and limewire
sudo aptitude install filezilla
#Limewire - download LimeWireLinux.deb from limewire site
# reports missing dependencies
sudo dpkg -i LimeWireLinux.deb
limewire-basic depends on sun-java6-jre | icedtea-java7-jre |
sun-java6-jdk | icedtea-java7-jdk; however:
Package sun-java6-jre is not installed.
Package icedtea-java7-jre is not installed.
Package sun-java6-jdk is not installed.
Package icedtea-java7-jdk is not installed.
dpkg: error processing limewire-basic (--install):
dependency problems - leaving unconfigured
Open synaptic package manager. Go to the Settings/Repositories/Other sources tab.
Check the two default partner sites. Reload the package list and select the following
sun-java6-jre
sun-java6-plugin
sun-java6-fonts packages
Now retry limewire and you’re smoking.
Installing ruby and associated gems
sudo apt-get install ruby
sudo apt-get install rubygems
sudo gem install rake
sudo gem install rails
I tried to install capistrano using sudo but it wasn’t working on laptop however it did work on desktop
Then change ~/.bashrc to include path to new gems
emacs ~/.bashrc &
export PATH=$PATH:~/.gem/ruby/1.8/bin:/var/lib/gems/1.8/bin
Now install and configure mysql before trying to install any of the ruby mysql gems
install mysql server
sudo apt-get install mysql-server
Setup prompts you for a password – enter it, remember it and enter it again.
Install the mysql admin tools
sudo apt-get install mysql-admin
NB – must install the libmysqlclient[nn]-dev package
This has mysql_config bundled with it which is needed by the ruby gems
Execute the following to find out what version of libmysqlclient you’re running
dpkg --get-selections | grep mysqlclient
In my case it’s version 16, so execute the following
sudo apt-get install libmysqlclient16-dev
Next, you NEED TO INSTALL the ruby1.8 dev package
If you don’t you’ll get all sorts of mysql gem errors — frustrating!!!
sudo apt-get install ruby1.8-dev
sudo gem install mysql
Installing and configuring git
sudo apt-get install git-core
git config --global user.email
Installing apache
sudo apt-get install apache2
The line above should do it, if you get any glitches, try the following
sudo apt-get install apache2.2-bin
sudo apt-get install apache2.2-common
sudo apt-get install apache2-threaded-dev
Installing php
sudo apt-get install php5
sudo apt-get install php5-mysql
Anything else is stuffing around with particular ruby gems and dev tools so probably too specific for this note.
No Comments // Posted on 3 July, 2010 // GNU/Linux, Ruby on Rails