我有一个有很多客户的用户模型。用户模型有一个整数属性eft_percent,而客户有一个布尔属性eft。创建该用户的客户时,我需要用户eft_percent属性进行更新。下面是我的代码:
after_action :calculate_eft, only: [:create]
def create
@customer = Customer.new(customer_params)
if @customer.save
flash[:notice] = 'Customer created'
redirect_to customers_url
else
flash[:alert] = 'Error creating customer'
redirect_to new_customer_url
end
end
private
def calculate_eft
@user = User.find(@customer.user_id)
@user.eft_percent = @user.customers.where(eft: true).count * 100 / @user.customers.count
@user.save
end创建客户时,用户eft_percent属性不会更改。感谢所有的帮助!
发布于 2014-12-19 22:19:27
这看起来更像是控制器而不是模型。因此,这是一个模型行为,因此,它应该在模型中:
customer.rb:
belongs_to :user
after_create {
newval = user.customers.where(eft: true).count * 100 / user.customers.count
user.update_attribute(:eft_percent, newval)
end要更新更多属性,只需传递一个散列即可。小心不要混淆用户和客户。哈希应该只包含用户属性。
user.update_attributes({attr1: val1, attr2: val2})或
user.update_columns({attr1: val1, attr2: val2})https://stackoverflow.com/questions/27574370
复制相似问题