簡體   English   中英

如何在子模型中獲取父對象ID? 嵌套表格

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

我有一個Campaign和一個Material模型。

class Campaign < ApplicationRecord
  has_many :materials

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

end

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

材質具有屬性代碼 ,我想在創建該屬性代碼時使用包含相關Campaign的ID的鏈接來填充該屬性代碼。

如何在Material模型中獲取對象Campaign

更新

抱歉,我講得不好。 在上述材料模型中,我想在“創建廣告系列過程”中獲取父ID來填充代碼屬性。

belongs_to :campaign而不是:campaigns ...使用單數形式,因為每種材料都是針對一個廣告系列。

定義belongs_tohas_many自動為您提供檢索對象的方法。

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 

如果您處於create campaign過程中,但尚未持久化該廣告活動,則您沒有要使用的ID,但是可以在廣告活動中使用after_save回調來解決此問題,該回調可以更新材料的code屬性帶有必要的ID。

使用before_save回調和self.campaign.id解決了該問題,以在處理用戶輸入的信息的方法中獲取父ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM