首页 > 解决方案 > 如何选择尚未保存在 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 []>

标签: ruby-on-railsassociationsform-forfields-for

解决方案


我能够想出一个答案。我曾尝试过“选择”,但我做错了。

我试过以下,

@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 } }

推荐阅读