【问题标题】:How do i select an association record that has yet to be saved in Rails?如何选择尚未保存在 Rails 中的关联记录?
【发布时间】:2020-05-15 01:02:06
【问题描述】:

我有以下模型和关系。我正在构建一个表单,并且想要初始化表单提案的条款。如何通过它的 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-rails associations form-for fields-for


    【解决方案1】:

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

    我尝试了以下方法,

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

    【讨论】:

      猜你喜欢
      • 2011-06-12
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多