Is this much logic in view is justified to check for the presence of record?
# device model
class Device < ApplicationRecord
validates :abbr, uniqueness: { case_sensitive: false }, presence: true
validates :name, presence: true
def abbr=(value)
self[:abbr] = value.to_s.strip
end
end
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 code
def 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?
Device
andDeviceVendor
? \$\endgroup\$Device
hasabbr
column which will be unique and this will be saved inDeviceVendor
notdevice_id
\$\endgroup\$