简体   繁体   中英

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"

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.

使用before_save回调和self.campaign.id解决了该问题,以在处理用户输入的信息的方法中获取父ID。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM