André Luiz
André Luiz

Reputation: 40

How can I get the parent object id inside the child model? Nested form

I hava a Campaign and a Material models.

class Campaign < ApplicationRecord
  has_many :materials

  accepts_nested_attributes_for :materials, reject_if: :all_blank, allow_destroy: true

end

and

class Material < ApplicationRecord
  belongs_to :campaign

  def code=(val)
    new_code = val
    suffixes = %w(.png .jpg .jpeg .gif .bmp)
    urls = URI.extract(new_code, ['http', 'https'])
    urls.each do |url|

      new_code = new_code.gsub(url, "#{url}&var1=#{self.campaign.id}") unless url.ends_with? *suffixes #<--- (this is not working
    end
    write_attribute(:code, new_code)
  end
end

Material has an attribute code, and I want to fill this attribute code with a link that contains the id of the related Campaign, while creating it.

How can I get the object Campaign inside the Material model?

UPDATE

Sorry, I didn't explain very well. In the above Material model I want to get the parent id to populate the code attribute, during the "create campaign process"

Upvotes: 0

Views: 949

Answers (2)

Andr&#233; Luiz
Andr&#233; Luiz

Reputation: 40

Solved it using a before_save callback and self.campaign.id to get the parent id inside a method to manipulate the info my user typed.

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

It's belongs_to :campaign not :campaigns ... use the singular since each material is for one campaign.

Defining belongs_to and has_many automatically gives you methods for retrieving the objects.

my_material = Material.first
my_material.campaign # <- this gives you the campaign object
my_material.campaign_id # <- this gives you the campaign object's id
my_material.campaign.id 
# ^ another way, slightly less efficient but more robust as you no longer need to know how the records are coupled 

If you're in the create campaign process and you haven't persisted the campaign, then you don't have an id to work with, but you can fix that with an after_save call back in the campaign that can update materials' code attribute with the necessary id.

Upvotes: 1

Related Questions