【问题标题】:Can I add a `after_add` callback to a ruby association in a model decorator?我可以在模型装饰器中向 ruby​​ 关联添加“after_add”回调吗?
【发布时间】:2017-05-11 21:49:56
【问题描述】:

关联是has_and_belongs_to_many,并在gem 中定义。我需要知道什么时候添加了一个新的,所以我可以告诉答案是after_add 回调,但事后我不知道如何添加它。

我现在的代码不起作用:

(在宝石中)

job.rb

module Spree
  class Job < Spree::Base
    has_and_belongs_to_many :users, join_table: 'spree_jobs_users', class_name: Spree.user_class.to_s
  end
end

(我的破代码)

job_decorator.rb

Spree::Job.class_eval do
  has_and_belongs_to_many :users, join_table: 'spree_jobs_users', 
class_name: Spree.user_class.to_s, after_add: :test

  def test
   # after method
  end
end

有什么方法可以实现吗?或者有什么其他方法可以让我知道何时添加了新工作?

【问题讨论】:

    标签: ruby-on-rails ruby spree spree-auth-devise


    【解决方案1】:

    如果您希望每次向spree_jobs_users 表添加一行时运行一些代码,在我看来代码应该是连接表的责任,而不是Spree::Job。我会将其重铸为has_many :through 关系,为您的连接表创建一个模型,并将您的代码放入该模型的:after_create 挂钩中。

    根据 Rails 文档,“最简单的经验法则是,如果您需要将关系模型作为独立实体使用,则应设置 has_many :through 关系。”

    http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 2011-08-10
      • 1970-01-01
      相关资源
      最近更新 更多