Quantcast
Viewing all articles
Browse latest Browse all 8

Display related records, if they exist, in Rails view

Is this much logic in view is justified to check for the presence of record?

# device modelclass Device < ApplicationRecord  validates :abbr, uniqueness: { case_sensitive: false }, presence: true  validates :name, presence: true  def abbr=(value)    self[:abbr] = value.to_s.strip  endend

Here is the code for DeviceVendor that also saves abbr column of Device to uniquely identify the device:

# model code class DeviceVendor < ApplicationRecord  validates :vendor, uniqueness: {scope: :device}end# controller codedef index  @device_vendors = DeviceVendor.order(:device, :vendor)end# 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.name if device %></td><td><%= vendor.name if vendor %></td><td><%= link_to 'Show', device_vendor %></td><td><%= link_to 'Edit', edit_device_vendor_path(device_vendor) %></td></tr><% end %>

What is the rails way to do this?


Viewing all articles
Browse latest Browse all 8

Trending Articles