Rails 3: Sending tempfiles for download
When you create a temporary file (e.g. to store a generated Excel sheet) and try to send it to the browser from a controller, it won't work by default. Take this controller action:
class FoosController < ApplicationController
def download
file = Tempfile.new('foo')
file.puts 'foo'
file.close
send_file file.path
end
end
Accessing this controller action will usually raise a 404 not found in the browser and the Apache log will say:
The given path was above the root path: xsendfile: ...
Effectively Using Materialized Views in Ruby on Rails · pganalyze
It's every developer's nightmare: SQL queries that get large and unwieldy. This can happen fairly quickly with the addition of multiple joins, a subquery and some complicated filtering logic. I have personally seen queries grow to nearly one hundred lines long in both the financial services and health industries.
Luckily Postgres provides two ways to encapsulate large queries: Views and Materialized Views. In this article, we will cover in detail how to utilize both views and materialized views within Ruby on Rails, and we can even take...
Security fixes for Rails 2.3
Last week saw a security issue with rails 2.3 that required a fix. While an official patch was provided, the 2.3 branch is no longer maintained. So we forked it.
(I'm sure there are already 100 other forks doing absolutely the same, but they are not very easily discoverable.)
To use our fork, change the gem "rails"...
line in your Gemfile to this:
gem 'rails', :git => 'https://github.com/makandra/rails.git', :branch => '2-3-fixes'
The intent is to make as few changes to the f...
Let a Rails 3 application make a request to itself
Ever wondered how Rails talks to itself in a Cucumber feature? In Rails 3 you can do it like this:
def rack_env(path)
{ "rack.input" => {},
"PATH_INFO"=>"#{path}",
"REQUEST_METHOD"=>"GET" }
end
request = rack_env('/users/new')
response = Rails.application.call(request)
status, headers, body = response
puts status # e.g. 200
puts headers.inspect # hash of headers
puts body.body # html of response body
Instead of Rails.application
you can also call any Rack application.
Rails 2.3.x sometimes renders localized views with the wrong content type
Under certain (unknown) circumstances, Rails will give localized files an invalid content-type in the Response header. For me, after requesting corporate_information
and rendering corporate_information.de.html.haml
, Rails sent a content-type of de.html
instead of the expected text/html
.
There are some discussions on this topic that offer workarounds, but no...
Fix warning "already initialized constant Mocha" with Rails 3.2
You either have an old version of Mocha and an edge version of Rails 3.2, or you have a new version of Mocha and an old version of Rails. The best solution is to update Mocha to the latest version and switch to Rails edge.
If you are using shoulda-matchers
or another gem that locks Mocha to an old version, you are out of luck.
More info with many other workarounds that you do not want to use can be found here. A hack to work around this case is to add the following file to lib/mocha/setup.rb
:...
Fix warning: Cucumber-rails required outside of env.rb
After installing Bundler 1.1 you will get the following warning when running tests:
WARNING: Cucumber-rails required outside of env.rb. The rest of loading is being defered until env.rb is called.\
To avoid this warning, move 'gem cucumber-rails' under only group :test in your Gemfile
The warning is misleading because it has nothing to do with moving cucumber-rails
into a :test
group. Instead you need to change your Gemfile
to say:
gem 'cucumber-rails', :require => false
MongoMapper for Rails 2 on Ruby 1.9
MongoMapper is a MongoDB adapter for Ruby. We've forked it so it works for Rails 2.3.x applications running on Ruby 1.9. [1]
makandra/mongomapper
is based on the "official" rails2
branch [2] which contains commits that were added after 0.8.6 was released. Tests are fully passing on our fork for Ruby 1.8.7, REE, and Ruby 1.9.3.
To use it, add this to your Gemfile
:
gem 'mongo_mapper', :git => 'git://github.com/makandra/mongomapper.git', :branch => 'rails2'
...
Riding Rails: Rails 4.0: Final version released!
Rails 4.0 is finally ready after a thorough process of betas and release candidates. It's an amazing new version packed with new goodies and farewells to old features past their expiration date.
Rails ERD – Entity-Relationship Diagrams for Rails
Gem to generate entity relationship diagrams from your Rails 3 ActiveRecord models. The diagram style is pretty and configurable.
How everyone is inserting technical debt in their applications | Plataforma Tecnologia Blog
This means Basecamp migrated from the first Rails release up to the edge one. So how come people say so frequently how hard is to update their applications from Rails 2.1 to Rails 2.2? And the answer is simple: plugins.
Bugfix: Rails 2 does not find an association when it is named with a string instead of a symbol
Association named 'variations' was not found; perhaps you misspelled it?
I just was hunting down a strange error with this model:
class Model
placeholder = 'variations'
has_many placeholder
nested_scope :verbose, :include => :variations
end
Everything, including Model.variations
and Model.reflect_on_all_associations.map &:name
did work (the latter returned [ :some_association, 'variations' ]
).
Eventually, the quotes led me to the solution: I had to write has_many placeholder.to_sym
.
...
ActionMailer sometimes breaks e-mails with multiple recipients in Rails 2
The ActionMailer in Rails 2 depends on a buggy version of TMail, which sometimes inserts a blank line into the mail header when sending a mail to multiple recipients. This makes the header end prematurely.
The reason why this is not exploding in your face all the time is that when you are relaying your e-mail through an MTA like Exim, it will fix this for you.
Fix for Rails if you don't have an awesome MTA
TMail is no longer maintained. The bug is fixed...
Rails Env Widget
Have you ever mistaken one Rails environment for another? The attached helper will help you to never do it again.
Save the attached file to app/helpers/ and use the widget in your layout like this:
%body
= rails_env_widget unless Rails.env.production?
It'll render a small light gray box in the top left corner of your screen, containing the current Rails environment. On click, it'll disappear. Actually, it has the same UX as our Query Diet widget.
Create a valid RSS feed in Rails
This will show you how to create a RSS feed that the Feed Validator considers valid.
Note that RSS is a poorly specified format. Consider using the Atom builder to make an Atom feed instead. Write a note here if you do.
- Controller
Create a FeedsController
to host the RSS feed. Such a controller is also useful to host other data feeds that tend to gather over the lifetime of an application, e.g. sitemap.xml
.:
class...
Passenger 5/6 requires a config.ru file to run Rails 2.3 projects
Put the following into config.ru
in your Rails root folder:
# Require your environment file to bootstrap Rails
require ::File.dirname(__FILE__) + '/config/environment'
# Dispatch the request
run ActionController::Dispatcher.new
Otherwise, your Rails 2.3 project will not be considered by Passenger 5+ and you will probably see 403 errors returned by nginx or Apache.
Default views in Rails 3.0 with custom resolvers
It is common in Rails 3.0 applications that you want to provide default views for a group of controllers. Let’s say you have a bunch of controllers inside the Admin namespace and you would like each action to fallback to a default template. So if you are rendering the index action for Admin::PostsController and “app/views/admin/posts/index.html.*” is not available, it should then render “app/views/admin/defaults/index.html”.
Since Rails 3.0, we have a new abstraction called resolvers that holds the logic to find a template.
Rails index route for resources named after uncountable substantives
Using uncountable resources is not recommended as it breaks Rails' magic, e.g. when using form_for
. You'll always be better off using simple pluralizable resources.
Rails automatically creates path names for routes defined via the resource
method. When you put resource 'user'
into config/routes.rb
, you can call users_path
and get the path to the index
action in the UsersController
: /users
.
However, if you have an uncountable resource like Sheep
, you cannot access the index action via sheep_path
, because it will...
Rails 3 ActiveRecord::Persistence#becomes does not copy changed attributes
Note: ActiveRecord::Base#becomes
has a lot of quirks and inconsistent behavior. You probably want to use ActiveType.cast
instead.
This issue will be encountered when relying on attribute_was
methods of ActiveModel::Dirty
after casting a model which has defaults to a form model, for example.
In my case a record with an assignable_values legacy value beca...
PostgreSQL vs. Rails migration: How to change columns from string to integer
When writing Rails migrations to convert a string
column to an integer
you'd usually say:
change_column :table_name, :column_name, :integer
However, PostgreSQL will complain:
PG::DatatypeMismatch: ERROR: column "column_name" cannot be cast automatically to type integer
HINT: Specify a USING expression to perform the conversion.
The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:
change_column :table_name, :column_name, 'i...
shoulda-matcher methods not found in Rails 4.1
So you're getting an error message like the following, although your Gemfile lists shoulda-matchers
and it has always worked:
NoMethodError:
undefined method `allow_value' for #<RSpec::ExampleGroups::Person::Age:0x007feb239fa6a8>
This is due to Rails 4.1 (specifically, Spring) revealing a weak point of shoulda-matchers
-- jonleighton explains why.
Solution
The solution is to follow [the gem's installation guide](https://github.com/thoughtbot/sh...
Rails 3.1.0 has been released!
jQuery as new default Javascript library, streaming response support, attr_accessible with roles, prepared statements, easier migrations.
Rails 3 issue: update_all ignores conditions, when :orders and :limit options are supplied
Leads to awesomeness and unicorns when used in production.
Use the contents of a WordPress database in your Rails app
These two models can be used to access the posts and associated comments of a WordPress database.