Quantcast
Viewing all articles
Browse latest Browse all 8

Answer by Sergio Tulentsev for Display related records, if they exist, in Rails view

You could also use first_or_initialize. It tries to find the record and, if not found, creates a new unsaved object (so that you always have an object and don't have to branch. This is called "confident code").

<% device = Device.where(abbr: device_vendor.device).first_or_initialize %><% vendor = Vendor.where(abbr: device_vendor.vendor).first_or_initialize %><tr><td><%= device.name %></td><td><%= vendor.name %></td>

Although I'm not a fan of queries in views like that. You should make proper activerecord relations there. Or, at least, move the queries to DeviceVendor's methods.

<td><%= device_vendor.device_or_default.name %></td><td><%= device_vendor.vendor_or_default.name %></td>

Viewing all articles
Browse latest Browse all 8

Trending Articles