0

我有四个相互关联的模型,如下所示:

class User < ActiveRecord::Base
    has_many :clients
    has_many :default_prices
end

class DefaultPrice < ActiveRecord::Base
    has_many :client_prices
    has_many :clients, :through => :user
    belongs_to :user
end

class Client < ActiveRecord::Base
    belongs_to :user
    has_many :client_prices
    before_create do
        user.default_prices.each do |default_price|
            client_prices.build("price" => default_price.price, "visit_type" => default_price.visit_type, "default_price_id" => default_price.id)
        end
    end
end

class ClientPrice < ActiveRecord::Base
    belongs_to :client
    belongs_to :default_price
end

现在,当用户创建新客户端时,用户的默认价格将应用于客户端的 client_prices 表。当用户创建新的 default_prices 时,如何创建新的 client_prices(针对每个现有客户端)?另外,当默认价格发生变化时,如何让 client_prices 更新?如果有帮助,每个客户价格都有一个与默认价格相关的 default_price_id 列。

4

1 回答 1

0
class DefaultPrice < ActiveRecord::Base
  before_create :new_client_price
  before_update :update_clients_price

private
    def new_client_price
  clients.each do |c|
    self.client_prices.create(:price => self.price, :visit_type => self.visit_type, :client_id => c.id)
        end
end

def update_clients_price
  self.client_prices.each do |p|
      p.price = self.price
        p.visit_type = self.visit_type
      p.save
  end
end
于 2013-01-28T17:29:23.113 回答