【问题标题】:How can I get the parent object id inside the child model? Nested form如何在子模型中获取父对象 ID?嵌套形式
【发布时间】:2017-03-21 15:18:19
【问题描述】:

我有一个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

Material有一个属性code,我想用包含相关Campaign的id的链接填充这个属性code,在创建它时。

如何在 Material 模型中获取对象Campaign

更新

对不起,我解释得不是很好。在上面的 Material 模型中,我想在 “创建活动过程”

期间获取父 ID 以填充代码属性

【问题讨论】:

    标签: ruby-on-rails ruby activerecord model nested-forms


    【解决方案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 属性。

    【讨论】:

    • 对不起,我没有很好地解释我的问题,我刚刚更新了我的问题。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多