Archive for 'Rails'
Search comma separated values db column in Rails
I wanted to search for a value in DB and the column data is comma separated values say …
foo,bar,hey,hay
Now I wanted to find a record based on the value …say …hay
MySQL’s FIND_IN_SET comes into play and it works as follows
Model.find(:first, :conditions => ["FIND_IN_SET(?,search_column)", search_string])
Hope this helps!
Making will_paginate to work with acts_as_taggable_on_steriods
After going through, few post on pagination for the tags, this worked for me.
<% size = Upload.find_tagged_with(params[:id]).length @uploads = Upload.paginate_tagged_with(params[:id], :total_entries => size, :page => params[:page], :per_page => 1) %>
Is Active
def is_active?
(start_date .. expiry_date) === DateTime.now
end
Run Controller Spec
Posted on February 21, 2009, under Rails, Shell Scripts.
If you just wanted to run only the controller specs, then you have to use the following command
rake spec:controllers
Select Random Records
I wanted for some reason to have random records from a model without any condition, just random records and here’s how you have to do it.
Hope this helps somebody!
Cheers!!!
Rails Default Layout
As we all know, for any controller, by default rails looks the controller name .rthml files and if it doesn’t exists then it looks application.rhtml.
Since my site is very simple, I don’t have many layouts and just one layout and so i stored the layout file in app/views/layouts/application.html.erb and i removed all other layout files so that by default it will read application.html.erb.
Hope this helps somebody!
Pads
Load Fixtures into the Database
I was looking to load the fixtures into my database and it is very simple. Please look at the following code
rake spec:db:fixtures:load
Hope this helps somebody.
Cheers!
Pads
Migartion in Different Envirnoments
Wanna run db:migrate command in other environments rather than development, then it is how so:
Test Environment
rake db:migrate RAILS_ENV=test
Production Environment
rake db:migrate RAILS_ENV=production
Obviously, these commands has to be executed from the root path of the application.
See ya
Hacking a nil object / Workaround
I was looking for a way to workaround a nil object. For instance if @project.name is nil, I wanted to display as “N/A” and otherwise the project name (@project.name)
Normal Way
<% unless @project.nil? %> <%= @project.name %> <% else %> <%= "N/A" %> <% end %>
Another Way
<%= @project.name rescue nil || "N/A" %>
Just in a one single line!, Neat ah
Hope this helps!
Reset button in Rails
I was looking for a way to have a reset button in the rails way, instead of the direct HTML tag.
<%= submit_tag "Start over", :name => "reset", :type => "reset", :id => "task_reset" %>