2017-03-21 26 views
0

我hava a 活動材料模型。如何獲取子模型內的父對象ID?嵌套形式

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 

材料有一個屬性,我想,以填補包含相關運動的ID的鏈接這個屬性代碼,同時創造它。

我怎樣才能得到對象運動裏面的材料模型?

UPDATE

對不起,我沒有很好地解釋。在上述材料模式,我想父ID來填充代碼屬性,在在「創建活動的過程」

回答

0

解決它使用before_save回調和self.campaign.id獲取方法內的父id來操縱我的用戶輸入的信息。

1

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回調的運動,可以使用必要的ID更新材料'code屬性。

+0

對不起,我沒有很好地解釋我的問題,我剛剛更新了我的問題。 –

+0

希望我的編輯能夠解決您的問題。 – SteveTurczyn