如何在 Rails 中存储根据名称获取的 ID?

How to store obtain id based on name in Rails?

我正在从事一个由进口组成的维护项目。

我的档案:

app/importers/contacts_importer.rb:

require 'csv'

class ContactsImporter < BaseImporter

  def import
    ..............
    sales_exec = fetch_value(row, "Sales Exec", :string) 
    email = fetch_value(row, "Email", :string) 
    ...................
        sales_exec_id = nil
        if sales_exec.present?
          sr = @file_import.account.users.where(initials: sales_exec).first
          sales_exec_id = sr.try(:id) if sr.present?
        end
        sales_exec_id = sales_exec_id 

        if company.present? 
          customer = Company.new
          customer.name = company
          customer.phone = phone
          customer.email = email
          customer.sales_exec = sales_exec_id
        end
  end

end

我的要求是我能够存储姓名、phone 和电子邮件但无法获取 sales_exec_id。 这里 sales_exec 是 role_name(销售主管、产品经理等)角色 table 的用户。 该关系是通过 user_roles(由 role_id 和 user_id 组成)的用户 has_many 角色。 有什么方法可以编写查询以在我的代码中使用 sales_exec_id.

匹配 sales_exec(显示 Venkat、John 等)

由于没有你的整个系统环境和csv文件,我建议两种方法。

    if sales_exec.present?
      sr = @file_import.account.users.where(initials: sales_exec).first
      sales_exec_id = sr.try(:id) if sr.present?
    end
  1. add puts sr add 查看终端中的输出

  2. 在终端中查看查询 SQL,您可以在 DB GUI 中调试它