ruby-on-rails - 如何选择尚未保存在 Rails 中的关联记录?
问题描述
我有以下模型和关系。我正在构建一个表单,并且想要初始化表单提案的条款。如何通过它的 term_type_id 选择特定的 ProposalTerm 以传递给我的 fields_for 块?
提议
class Proposal < ApplicationRecord
after_initialize :add_terms
has_many :terms, class_name: "ProposalTerm", dependent: :destroy
accepts_nested_attributes_for :terms
def add_terms
terms << ProposalTerm.first_or_initialize(type: TermType.signing_bonus)
end
end
提案期限
class ProposalTerm < ApplicationRecord
include DisableInheritance
belongs_to :proposal
belongs_to :type, class_name: "TermType", foreign_key: "term_type_id"
def self.signing_bonus
find_by(type: TermType.signing_bonus)
end
end
我的尝试
>> @proposal.terms
=> #<ActiveRecord::Associations::CollectionProxy [#<ProposalTerm id: nil, season: nil, value: nil, is_guaranteed: false, term_type_id: 2, proposal_id: nil, created_at: nil, updated_at: nil>]>
>> @proposal.terms.where(term_type_id: 2)
=> #<ActiveRecord::AssociationRelation []>
解决方案
我能够想出一个答案。我曾尝试过“选择”,但我做错了。
我试过以下,
@proposal.terms.select(term_type_id: 2)
但这并没有返回任何东西。然后我做了以下...
@proposal.terms.select { |t| t.term_type_id = 2 }
如果您只想返回第一个实例,请使用“检测”...
@proposal.terms.detect { |t| t.term_type_id = 2 } }
推荐阅读
- pdf - 由inkscape创建的PDF包含通过虚线的细灰线
- python - 如何简化具有两个不等式的表达式:如果 x <= y 和 x >= n
- python - 数据框和循环
- javascript - 引导模式淡出窗口但不弹出
- python - 如何在 Python Selenium 中按类名查找元素?
- azure - Azure 数据资源管理器 - 日志查询
- java - 如何在 androidTest(仪表测试)测试类中从我的应用程序访问资源?
- c# - 将 IEnumerable 转换为 List 以符合方法签名
- python - 在 Heroku 上部署 Django 项目:ModuleNotFoundError
- node.js - Websocket 客户端 perl 与 Node.js