【问题标题】:How to store obtain id based on name in Rails?如何在Rails中存储基于名称的获取ID?
【发布时间】:2016-03-28 04:51:55
【问题描述】:

我正在从事一个包含导入的维护项目。

我的文件:

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

我的要求是我能够存储姓名、电话和电子邮件,但无法获取 sales_exec_id。 这里 sales_exec 是角色表中具有角色名称(销售主管、产品经理等)的用户。 关系是通过 user_roles 的用户 has_many 角色(由 role_id 和 user_id 组成)。 有没有办法编写查询以匹配我的代码中的 sales_exec(显示 Venkat、John 等)与 sales_exec_id。

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    由于没有你的整个系统环境和 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 中对其进行调试

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2010-12-31
      • 2011-11-13
      • 2012-08-12
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      相关资源
      最近更新 更多