On 29 June 2010 08:40, Carsten G. [email protected] wrote:
What I would like is to convert
<%[email protected]%>
to
<%=(@post.user.name) rescue ‘’%>
No it’s not. You shouldn’t use exceptions to handle non-exceptional
behaviour - and if you know that some posts have had their user
deleted, then it’s not exceptional
Besides, this all needs to be done in the model or controller, as the
view should be blissfully ignorant about any data integrity problems
you might have.
Is there any way to override <%= to do the above? Thus fixing all errors
on the spot.
I use a method of substituting a mock object (I’d call it MissingUser
in this instance) which has accessors for each of the properties that
I need from the real AR object that’s missing. I then instanciate one
of the mock objects if I request a child object that’s missing, by
overloading the call to the associated object, and adding a check that
it exists.
missing_user.rb
just a normal Ruby model, but not AR-backed
class MissingUser
attr_accessor :name, :dob # …etc (any fields you know you need)
# as well as accessors you can set default values for parameters,
so every new instance gets populated with some values
def name
@name || “Missing User”
end
end
post.rb
class Post < ActiveRecord::Base
has_one :user
alias_method :ar_user, :user # alias the ActiveRecord call
def user
@user || = (ar_user || MissingUser.new) # memoized to save
creating a new MissingUser for every call to the method
# you could also pass in default values as parameters for the
“new” if you wanted - just overload MissingUser’s initialize method
end
end
Does that make sense?
I apologise for any typos or mistakes in the code above, as I’ve just
written it in the email and haven’t run it to test. But I hope you can
get the gist from what’s there.