【发布时间】: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