NULLs and model relationships

What is the accepted idiom for displaying database rows that contain
NULLs in their foreign key reference to another table? Very simplified
example:

SQL:
CREATE TABLE topics (id integer, name varchar);
CREATE TABLE posts (id integer, topic_id integer, post text);

Rails Models:
class Topic < ActiveRecord::Base
has_many :post
end
class Post < ActiveRecord::Base
belongs_to :topic
end

Rails View:
<% for post in @posts %>
<%= h post.post %>
<%= h post.topic.name %> <-------- idiom in question
<% end %>

Of course, if the topic_id column in the post is null, then we end up
with a nil object that doesn’t understand ‘name’. I could put
<%= post.topic ? h post.topic.name : ‘Unknown’ %>
at every place in the view, but this seems a little inelegant. Is there
a better idiom for this, perhaps to tell the model about the default
display values?

thanks
-Worky

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