【问题标题】:How to use finder methods on join table values?如何在连接表值上使用查找器方法?
【发布时间】:2018-11-12 11:15:25
【问题描述】:

在我的 Ruby on Rails 应用程序中,我在我的数据库中创建了一个连接表来链接客户和企业。现在我正在尝试根据连接表中的信息(称为“冲突”)查找有关其中一个模型的信息:

@customer = Customer.where(customer_id: 1).conflict(s) @customer = Customer.find(1).conflict(s)

我想查找与给定“冲突”直接相关的客户(或企业)的信息,并将其打印到浏览器视图中。

我现在遇到的错误: # 的未定义方法“冲突”

【问题讨论】:

  • 您能告诉我们您的关联是如何定义的吗?

标签: ruby-on-rails activerecord jointable


【解决方案1】:

要通过客户获得冲突,您应该在客户模型(customer.rb)中具有以下关联,

has_one :冲突 要么 has_many : 冲突

【讨论】:

  • 感谢您的回复....我正在尝试更新模型,但不断收到 NameError。即使在我删除了数据库之后。我最近在我的项目文件夹中安装了设计和 OAuth。是否有更新模型并将数据存储在我的种子中以用于测试应用程序的解决方法?
  • 你能分享你的架构吗?
【解决方案2】:

根据提供的描述,您创建了一个包含客户和企业参考的连接表。

而且你提供的错误,好像你忘记在你的模型中关联它们了。

客户.rb

class Customer < ApplicationRecord
  has_many :customer_conflicts
  has_many: conflicts, through: :customer_conflicts
end

conflict.rb

class Conflict < ApplicationRecord
   has_many :customer_conflicts
   has_many :customers, through: :customer_conflicts
end

customer_conflict.rb

class CustomerConflict < ApplicationRecord
 belongs_to :customer
 belongs_to :conflict
end

现在运行下面提到的查询将起作用:

@customer = Customer.where(customer_id: 1).conflicts
@customer = Customer.find(1).conflicts

【讨论】:

  • 感谢您的回复....我正在尝试更新模型,但不断收到 NameError。即使在我删除了数据库之后。我最近在我的项目文件夹中安装了设计和 OAuth。是否有更新模型并将数据存储在我的种子中以用于测试应用程序的解决方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
  • 2020-04-27
  • 2013-01-01
相关资源
最近更新 更多