使用与父项相同的数据更新子模型

时间:2013-01-28 16:57:19

标签: ruby-on-rails

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

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列,与默认价格相关,如果有帮助的话。

1 个答案:

答案 0 :(得分: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