简体   繁体   English

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

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

I hava a Campaign and a Material models. 我有一个Campaign和一个Material模型。

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. 材质具有属性代码 ,我想在创建该属性代码时使用包含相关Campaign的ID的链接来填充该属性代码。

How can I get the object Campaign inside the Material model? 如何在Material模型中获取对象Campaign

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" 在上述材料模型中,我想在“创建广告系列过程”中获取父ID来填充代码属性。

It's belongs_to :campaign not :campaigns ... use the singular since each material is for one campaign. belongs_to :campaign而不是:campaigns ...使用单数形式,因为每种材料都是针对一个广告系列。

Defining belongs_to and has_many automatically gives you methods for retrieving the objects. 定义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 

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. 如果您处于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