如何从id获取用户名

时间:2022-01-01 20:32:20

I want to get the name of the caller by the caller_id. Name is in the user table.

我想通过caller_id获取调用者的名字。名称位于用户表中。

Here's the migration file.

这是迁移文件。

class AddCallerIdToSeller < ActiveRecord::Migration
  def change
    add_column :users, :caller_id, :string
  end
end

This is the view that I am currently doing.

这是我目前正在做的观点。

 <td class="text-center"><%= call_report.caller_id.present? %></td>

When i do like above, it shows true. But I want to get the user name which is "=" caller_id

当我喜欢上面的时候,它表明了真实。但我想获得用户名为“=”caller_id

2 个解决方案

#1


1  

User.find(call_report.caller_id).name

The best way to do this in the controller and assign it to some variable there.

在控制器中执行此操作并将其分配给某个变量的最佳方法。

#2


1  

If you do this...

如果你这样做......

class CallReport < ApplicationRecord
  belongs_to :user
end

You can then do

然后你可以做

call_report.user.name

Also the ID is normally stored as an integer, so it's more typical to see...

此外,ID通常存储为整数,因此更常见的是......

add_column :users, :caller_id, :integer

I'd do a rake db:rollback then make the above change then rake db:migrate

我做了一个rake db:rollback然后进行上面的更改然后rake db:migrate

#1


1  

User.find(call_report.caller_id).name

The best way to do this in the controller and assign it to some variable there.

在控制器中执行此操作并将其分配给某个变量的最佳方法。

#2


1  

If you do this...

如果你这样做......

class CallReport < ApplicationRecord
  belongs_to :user
end

You can then do

然后你可以做

call_report.user.name

Also the ID is normally stored as an integer, so it's more typical to see...

此外,ID通常存储为整数,因此更常见的是......

add_column :users, :caller_id, :integer

I'd do a rake db:rollback then make the above change then rake db:migrate

我做了一个rake db:rollback然后进行上面的更改然后rake db:migrate