Why does a Rails orphan merge records for polymorphic ones through associations?

The proposal document can be divided into several different types of sections (text, fees, schedule), etc.

Here he is modeled using the polymorphic association in the compound table.

class Proposal < ActiveRecord::Base
  has_many :proposal_sections
  has_many :fee_summaries, :through => :proposal_sections, :source => :section, :source_type => 'FeeSummary'
end

class ProposalSection < ActiveRecord::Base
  belongs_to :proposal
  belongs_to :section, :polymorphic => true
end

class FeeSummary < ActiveRecord::Base
  has_many :proposal_sections, :as => :section
  has_many :proposals, :through => :proposal_sections 
end

So far, #create is working fine.

summary = @proposal.fee_summaries.create
summary.proposal == @propsal # true

#new doesnt

summary = @proposal.fee_summaries.new
summary.proposal -> nil

Should it return zero?

In the usual has_many and belongs to the initialized, but non-repetitive records will still return their parent association (internal memory).

Why is this not working and not intended for this?

schema.rb

 create_table "fee_summaries", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "proposal_sections", :force => true do |t|
    t.integer  "section_id"
    t.string   "section_type"
    t.integer  "proposal_id"
    t.datetime "created_at",   :null => false
    t.datetime "updated_at",   :null => false
  end

  create_table "proposals", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

ruby 2.0 rails 3.2.14

+4
source share
1 answer

ActiveRecord , request.fee_summaries - fee_summary.proposal. , , .. - , , , . inverse_of . :

class Proposal < ActiveRecord::Base
  has_many :proposal_sections, :inverse_of => :proposal
end

class ProposalSection < ActiveRecord::Base
  belongs_to :proposal, :inverse_of => :proposal_sections
end

2.0.0-p353 :001 > proposal = Proposal.new
 => #<Proposal id: nil, created_at: nil, updated_at: nil> 
2.0.0-p353 :002 > section = proposal.proposal_sections.new
 => #<ProposalSection id: nil, proposal_id: nil, created_at: nil, updated_at: nil> 
2.0.0-p353 :003 > section.proposal
 => #<Proposal id: nil, created_at: nil, updated_at: nil> 

, inverse_of (through) . . , , ( create), AR .

: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods

+3

Source: https://habr.com/ru/post/1533655/


All Articles