Display optional db data

ive got a few models that may or may not have some data: urls / phone
numbers / dates / times / etc
whats the best way to test and format this data for displaying on a
webpage?

the way im thinking of doing it would be a few lines of code to:

  • test if not null
  • format properly
  • display in proper div / ul container

and then do that for each thing
is there a cleaner way to do this?

could someone perhaps advise on how to move some of this logic from
view to model?
like ‘get_price_info’ and it returns the properly formatted string or
nothing?
or should these tests be performed in the view?

On Thu, Apr 15, 2010 at 11:05 AM, dan [email protected] wrote:

could someone perhaps advise on how to move some of this logic from
view to model?
like ‘get_price_info’ and it returns the properly formatted string or
nothing?
or should these tests be performed in the view?

I’m not sure what you’re looking for here; if you have a view with e.g.
<%= @thing.foo %>
and this particular “foo” is nil, nothing will display, otherwise you
get
the value of “foo”.

If that’s not the behavior you want, please describe in more detail.


Hassan S. ------------------------ [email protected]
twitter: @hassan

if thing.foo is a date, price, url or something else that requires
formatting, it requires more than =thing.foo
and since you cant format nil, a test needs to be performed before
trying to format said data
my views are getting littered with these tests and formats, sometimes
there nested:
is there price data?
is there an advance purchase price?
is there an advance purchase expiry date?

its getting kinda ugly in my view
whats the best way to handle this?

On Thu, Apr 15, 2010 at 11:36 AM, dan [email protected] wrote:

if thing.foo is a date, price, url or something else that requires
formatting, it requires more than =thing.foo
and since you cant format nil, a test needs to be performed before
trying to format said data
my views are getting littered with these tests and formats, sometimes
there nested:

Some possible approaches:

  1. make the default in the database some value other than null.

  2. <%= @thing.foo.format rescue nil %>

  3. <%= @thing.foo.nil? ? " N/A " : @thing.foo.format %>

I’m sure someone will suggest others, but HTH :slight_smile:


Hassan S. ------------------------ [email protected]
twitter: @hassan

The logic for this probably belong in view helpers and not in the
model since its really about how the data is displayed and not about
how the data behaves.

It would be easier if you post the actual view code, and then somebody
can show you how you might refactor it by moving logic into helpers

anyone have a good example of how best to move this logic to a helper?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs