link_to_has_one
April 16th, 2008 • Uncategorized
# Creates 'Show AssociatedResource' or 'New AssociatedResource' links
# based on wether the specified has_one association exists or not.
# The optional options parameter is passed through to link_to as html_options.
# Since this helper relies on record identification, there is no way to pass
# all the other url_for options, as far as I can see
# ---------------------------------------------------------------------------
# Use in your views like so:
# <%= link_to_has_one @post, :comment %>
# <%= link_to_has_one @post, :comment, "What say you?" %>
# <%= link_to_has_one @post, :comment, "What say you?", :class => "oldskool" %>
def link_to_has_one(parent, has_one_association_name, options = {})
has_one_association_name = has_one_association_name.to_s.underscore
child = has_one_association_name.camelize
child_path = "#{parent.class.to_s.underscore}_#{has_one_association_name}_path"
if parent.send(has_one_association_name)
name = options[:new_name] ? options[:new_name] : "Show #{child}"
link_to name, self.send(child_path, parent), options
else
name = options[:existing_name] ? options[:existing_name] : "New #{child}"
link_to name, self.send("new_#{child_path}", parent), options
end
end