On 13 December 2010 16:30, Rob Biedenharn <[email protected]> wrote:
> Or, you can push that into the model and avoid the extra logic in the view:
> class Post
> def user_name
> self.user ? self.user.name : "(none)"
> end
> end
Instead of creating a new method to delegate from the associated
object, I rather overload the association with a blank object if a
legitimate associated object is missing, which has the benefit of
allowing me to still use method chains in my views, but to also set
default values for missing objects:
alias_method :activerecord_user, :user
def user
activerecord_user || User.new(:name => "(none)")
end
There are a few gotchas... most of which I avoid by creating a new
"User", but not assigning it as an association (more object
instanciation, but if it was a real problem, I could assign it to an
instance variable...). As a balance between reducing the checks in the
view and creating (potentially) confusing methods, it does the job on
occasion.
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.