【问题标题】:How to display name instead of user_id in a datatable in Rails如何在 Rails 的数据表中显示名称而不是 user_id
【发布时间】:2020-03-03 05:05:23
【问题描述】:

几天来,我在应用程序中遇到了一个问题,这让我思考了很多: 我有一个名为“Devices”的数据表,其中包含对“Users”的引用,在我的数据表中我带回了“user_id”,但我想在后端获取该数据并在前端显示“用户名”。

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

在“user”列中托管“user_id”

在我的 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"

在我的 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

在我的 user.rb 中

class User < ApplicationRecord
has_many :devices
end

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3 datatable devise


【解决方案1】:

好的 My question is duplicated. Here

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

【讨论】:

  • 如果没有includes,您每次访问设备用户时都会进行查询。该答案不能解决您问题中所述的“问题”。这是在没有适当约束的情况下在数据库或应用程序中应用方法的结果。这是为了给未来的读者提供建议。
  • 谢谢你,我正在调查,你是对的,谢谢你的贡献
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多