You can use try
:
Address: <%= record.address.try(:addresslineone) %>
This will return nil
if either of address
or address.addresslineone
is nil.
質問
I honestly looked for the answer to this basic question and didn't find anything. I often get a "NoMethodError" whn first making an app that has related records. Sometimes the first records aren't related to another table as it didn't exist at the time. To prevent this I've started adding 'if' blocks around alot, but figure there is probably a much cleaner wayt o do this. Here is an Example:
Name: <%=record.name%>
Address: <%= record.address.addresslineone %>
this above might crash if there is no address for the record. So I replace it with:
Name: <%=record.name%>
Address: <% if record.address %><%= record.address.addresslineone %><% end %>
I'm sure there is a much better way to be going about this how I'm approach it. I lay out my ignorance before you and ask for help and kindness;-)
Mark
解決
You can use try
:
Address: <%= record.address.try(:addresslineone) %>
This will return nil
if either of address
or address.addresslineone
is nil.