HUSTEN
HUSTEN

Reputation: 5197

How can I design the view assuming when the value is nil?

I'm newbie to Rails.

By now,I figured out how to make model, controller, views, and routing.

The problem that I'm facing now is, how to design code in views when the value is nil.
Obviously, it gives back error when the reffered value is nil.

For now, at every single part, I'm coding just like this to avoid error.
Is this normal thing to do???

Especially, I'm using acts_as_paranoid for logical deletion.
So in most cases, this kind of things would happen to my rails app.

  <% if @messages.sender %>  
    <%= @messages.sender.user_profile.nickname %> (<%= @messages.sender.username %>)
  <% else %>
    Resigned User!
  <% end %>

Upvotes: 1

Views: 36

Answers (1)

siddick
siddick

Reputation: 1478

You can write helper method do avoid code duplication.

In helper:

def sender_name(msg)
  if msg.sender
    "#{msg.sender.user_profile.nickname} (#{msg.sender.username})"
  else
    "Resigned User!"
  end
end

In View: <%= sender_name(@message) %>

Upvotes: 2

Related Questions