我如何选择尚未保存在Rails中的关联记录?

问题描述 投票:0回答:1

我有以下模型和关系。我正在构建一个表单,并希望为该表单初始化提案的条款。如何通过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

ProposalTerm

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-rails associations form-for fields-for
1个回答
0
投票

我能够找出答案。我曾尝试过“选择”,但操作不正确。

我尝试过以下方法,

@proposal.terms.select(term_type_id: 2)

但是那没有返回任何东西。然后我做了以下...

@proposal.terms.select { |t| t.term_type_id = 2 }

如果只想返回第一个实例,请使用“ detect” ...

@proposal.terms.detect { |t| t.term_type_id = 2 } }
© www.soinside.com 2019 - 2024. All rights reserved.