![](/img/trans.png)
[英]How can I access an ActiveRecord grandparent association through a parent association that has not yet been saved?
[英]How do i select an association record that has yet to be saved in Rails?
我有以下模型和關系。 我正在構建一個表單,並且想要初始化表單提案的條款。 如何通過它的 term_type_id select 一個特定的 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 } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.