【问题标题】:Rails update one models attribute from different models create actionRails 从不同的模型更新一个模型属性创建动作
【发布时间】:2014-12-20 16:19:38
【问题描述】:

我有一个有很多客户的用户模型。用户模型有一个整数属性eft_percent,客户有一个布尔属性eft。当创建此用户的客户时,我需要更新 users 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 属性没有改变。感谢所有帮助!

【问题讨论】:

  • 不应该调用@user.save 作为calculate_eft 中的最后一行来将新值保存到数据库中吗?
  • 我试过它不起作用(我想我在帖子中提到过)。我想知道我是否需要做 update_attributes 什么的。
  • 如果您从以下位置打印值,您是否得到正确的结果:'@user.customers.where(eft: true).count * 100 / @user.customers.count'?
  • 我更改了帖子以反映@user.save。同样,它不起作用。用户 eft_percent 没有改变。
  • 是的,我可以将代码放在用户显示视图中并且它可以工作,但是我有一堆属性我需要做同样的事情,所以我需要让他们成为用户属性,所以我不必在每次加载视图时都计算所有这些。如果在创建客户时完成计算,则可以节省加载视图时必须即时执行的时间。

标签: ruby-on-rails


【解决方案1】:

这看起来更像是一个控制器而不是一个模型。所以,这是一种模型行为,因此,它应该在模型中:

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})

【讨论】:

  • 我只需要更新这个客户所属的用户,这个代码并没有定义哪个用户得到更新,对吧?我将如何更新客户所属的特定用户属性?
  • usercurrent_object.user (self.user) 的简写,因为型号为 belongs_to :user。它只会更新客户所属的用户。
  • 很高兴它对你有用。正确处理关联可以为您节省大量工作。
  • 还有一个问题:在您的示例中,我将如何更新多个属性的属性?只需执行 user.update_attributes(:eft_percent, eft_val, :other_stat, other_val) 还是将它们放入哈希中,或者对多个属性执行此操作的最佳方法是什么?
  • 我尝试了我提到的方法并尝试了哈希,但都没有奏效。现在我只是为每个属性复制你的代码,但必须有一种更简洁的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
相关资源
最近更新 更多