【问题标题】:Rails Model.find is treating id as array. How do I get this to a act like a regular id?Rails Model.find 将 id 视为数组。我怎样才能让它像普通身份证一样?
【发布时间】:2021-09-08 06:00:24
【问题描述】:

我想对产品使用公司模型中的方法,如下所示:

 def internal_email_recipients
    product = Product.find(params[:id])
    company = Company.find([product.producer.id])
    company.plant_coordinator_emails.reject {|a| a == current_user.contact.email}
  end

但是,当我这样做时,我收到一个错误:

#Array:0x7fd5bc521108 的未定义方法“plant_coordinator_emails”

模型关联是:

class Product < ActiveRecord::Base
  
  belongs_to :producer, :class_name => 'Organization'
class Producer < Organization
  
  has_many :products, :dependent => :destroy, :order => 'products.name'

class Company < Producer

其中包含方法

def plant_coordinator_emails
    plants.map {|plant| plant.coordinator.telcom.email if plant.coordinator}.compact.reject{|p| p == ''}.uniq.join(', ')
  end

我认为它应该返回与生产者具有相同 id 的公司的所有属性。只有一个公司具有此 ID。

为什么 Rails 将其视为数组而不是 id?

【问题讨论】:

  • 您将一组 ID 传递给 Company.find,因此 find 将返回一组结果 Company 对象。只需取出数组括号即可。

标签: ruby-on-rails model-associations


【解决方案1】:

您正在将一个数组传递给company = Company.find([product.producer.id]) 只需使用company = Company.find(product.producer.id)(没有[]

【讨论】:

  • 与此同时,我还尝试将 has_one :company, :class_name =&gt; 'Company', :foreign_key =&gt; 'id' 添加到 Producer.rb 并执行 product.producer.company.plant_coordinator_emails - 它有效,但您的答案似乎更有机。
  • foreign_key 应该是 company_id,或者更好的是,删除该选项并让 rails 使用约定,因为您没有覆盖它。与class_name相同,只需将其删除并将关联定义为has_one :company
  • 谢谢你,费尔。我实际上已经尝试过并得到了Mysql error。有趣的是 - company_id 没有引用单独的表。编写该应用程序的人设置了organizations 表的子类别,例如公司、工厂、认证者。这些由type 列确定。
猜你喜欢
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
  • 2014-09-07
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多