For some reason the Squirrel plugin is producing two different results
between Mongrel and Passenger.
Mongrel serves up the page with no problems and no errors in the
development log.
Passenger gives the following error:
NoMethodError in ContractsController#index
undefined method `username’ for nil:NilClass
Below is my setup in relevant part.
contracts_controller.rb:
…
def index
if admin?
@contracts = Contract.find(:all)
else
@contracts = Contract.find(:all) do
user.username == current_user.username
end
end
end
…
end
I have also tried ‘self.user.username == current_user.username’
without success.
contract.rb:
class Contract < ActiveRecord::Base
…
belongs_to :user
…
end
user.rb:
class User < ActiveRecord::Base
acts_as_authentic
…
has_many :contracts
…
end
Not sure what the problem is. Would appreciate some help.
-Alexis
Ok, so I’m an idiot. I thought it was the first part of the Squirrel
block that was the problem. But it wasn’t. I figured it out when it
became apparent that the code wouldn’t work when the user wasn’t
logged in.
Obviously the problem was that I was comparing user.username to
current_user.username, when current_user was not set because no user
was logged in.
Here’s the code that appears to be working properly. I should write
some tests to make sure.
def index
checks to see if current_user is defined (via Authlogic) and if
its role
is “admin”. Then find all contracts.
if admin?
@contracts = Contract.find(:all)
checks to see if a user is logged in then uses Squirrel to find
only
those contracts whose username is the same as the current user.
elsif logged_in?
@contracts = Contract.find(:all) do
user.username == current_user.username
end
if the user is not logged in calls Authlogic’s login_required to
make the user log in.
else
login_required
end
end
At first, I thought I should go with nested resources here, nesting
Contracts under Users, but then I turned to this solution to allow
admin users to see Contracts that they didn’t create. I’m sure there’s
better ways. I am open to suggestion.
If you are at all curious, what Thoughtbot’s Squirrel plugin allows
you to do is to (from their site): “Squirrel is an enhancement for
ActiveRecord’s find method that allows programmers to query the
database using a more Rubyish syntax.”
You can find more details here:
http://wiki.github.com/thoughtbot/squirrel/
I’m still not sure why it worked for Mongrel, but now it works both
ways.
-Alexis M.