2012-12-16 45 views
0

我有以下表格:用戶,默認價格,客戶,客戶價格。我希望在創建新客戶端時使default_prices自動填充client_prices表。看起來我可能會使用類似this answer的解決方案。我想要發生的是當用戶創建新客戶端時,客戶端的所有client_prices都由default_prices表填充。如何基於默認表插入多行?

class User < ActiveRecord::Base 
    attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :stripe_token, :default_prices_attributes 
    has_many :default_prices 
    has_many :clients 
    accepts_nested_attributes_for :default_prices, :allow_destroy => true 


class DefaultPrice < ActiveRecord::Base 
    attr_accessible :price, :user_id, :visit_type, :id 
    belongs_to :user 
end 


class Client < ActiveRecord::Base 
    attr_accessible :active, :address_1, :address_2, :city, :email, :first_name, :last_name, :state, :user_id, :zip, :client_prices_attributes 
    belongs_to :user 
    has_many :client_prices 
    accepts_nested_attributes_for :client_prices_attributes 


class ClientPrice < ActiveRecord::Base 
    attr_accessible :price, :client_id, :visit_type, :id 
    belongs_to :uclient 
end 

回答

0

您可以添加before_create塊來複制默認價格。

before_create do 
    user.default_prices.each do |default_price| 
    client_prices.build(default_price.attributes.slice("price", "visit_type")) 
    end 
end