Ruby on rails 如何在Rails的数据表中显示名称而不是用户id

Ruby on rails 如何在Rails的数据表中显示名称而不是用户id,ruby-on-rails,ruby,ruby-on-rails-3,datatable,devise,Ruby On Rails,Ruby,Ruby On Rails 3,Datatable,Devise,几天来,我在申请中遇到了一个问题,这让我有很多事情要考虑: 我有一个名为“设备”的数据表,其中包含对“用户”的引用,在我的数据表中,我带回了“用户id”,但我想在后端获取该数据,并在前端显示“用户名” 我怎样才能得到预期的结果 在“用户”列中,托管“用户id” 在my index.html.haml中: .table__wrapper = form_tag edit_multiple_devices_path, method: :get do %table{:role =&

几天来,我在申请中遇到了一个问题,这让我有很多事情要考虑: 我有一个名为“设备”的数据表,其中包含对“用户”的引用,在我的数据表中,我带回了“用户id”,但我想在后端获取该数据,并在前端显示“用户名”

我怎样才能得到预期的结果

在“用户”列中,托管“用户id”

在my index.html.haml中:

.table__wrapper
    = form_tag edit_multiple_devices_path, method: :get do
      %table{:role => 'datatable'}
        %thead
          %tr
            %th
            %th.abbr{:title => "aidi"} Id
            %th.abbr{:title => "imei"} Imei
            %th.abbr{:title => "brand"} Marca
            %th.abbr{:title => "model"} Modelo
            %th.abbr{:title => "prov"} Proovedor
            %th.abbr{:title => "fac"} Factura
            %th.abbr{:title => "din"} Entrada
            %th.abbr{:title => "sim"} Sim
            %th.abbr{:title => "iccid"} Iccid
            %th.abbr{:title => "status"} Status
            %th.abbr{:title => "user_id"} Usuario
            %th.abbr{:title => "client"} Cliente
            %th.abbr{:title => "dout"} Salida
            %th.abbr{:title => :use} Usado
            %th.abbr{:title => :old} Reutilizado
          %tbody
            - @devices.each do |device|
              %tr
                %td= check_box_tag "device_ids[]", device.id
                %td= device.aidi
                %td= device.imei
                %td= device.brand
                %td= device.model
                %td= device.prov
                %td= device.fac
                %td= device.din
                %td= device.sim
                %td= device.iccid
                %td= device.status
                %td= device.user_id
                %td= device.client
                %td= device.dout
                %td= device.use
                %td= device.old
      = submit_tag "Editar", class: "button is-primary is-rounded"
在my device.rb中

class Device < ApplicationRecord
belongs_to :user
attr_accessible :aidi, :imei, :brand, :model, :prov, :fac, :din, :sim, :iccid, :status, :user_id, :client, :dout, :use, :old
end
类设备
在my user.rb中

class User < ApplicationRecord
has_many :devices
end
class用户
正常


即时的“解决方案”是%td=device.user.try:email

不包含
includes
您每次访问设备用户时都在执行查询。这个答案并不能解决你问题中提到的“问题”。它是在没有适当约束的情况下在数据库或应用程序中应用方法的结果。这是给未来读者的建议。谢谢你,我正在调查,你是对的,谢谢你的贡献。副本: