【发布时间】: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