Quantcast
Channel: Display related records, if they exist, in Rails view - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 8

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

$
0
0

Using try method of ruby, exception will not be raised and nil will be returned instead, if the receiving object is a nil object.

Try below code in view:

# view code<% @device_vendors.each do |device_vendor| %><% device = Device.where(abbr: device_vendor.device).first %><% vendor = Vendor.where(abbr: device_vendor.vendor).first %><tr><td><%= device.try(:name) %></td><td><%= vendor.try(:name) %></td><td><%= link_to 'Show', device_vendor %></td><td><%= link_to 'Edit', edit_device_vendor_path(device_vendor) %></td></tr><% end %>

OR correct way is to add association

Device has_many_and_belongs_to VendorVendor has_many_and_belongs_to Device

DeviceVendor is Join table of Device and Vendor


Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>