ruby-on-rails - 在 Rails 中实例化对象时如何初始化属性?

标签 ruby-on-rails model attributes initialization dry

客户有很多发票。发票有一个 number 属性,我想通过增加客户以前的发票编号来初始化它。

例如:

@client = Client.find(1)
@client.last_invoice_number
> 14
@invoice = @client.invoices.build
@invoice.number
> 15

我想将此功能添加到我的 Invoice 模型中,但我不确定如何操作。这是我想象中的代码:

class Invoice < ActiveRecord::Base
  ...
  def initialize(attributes = {})
    client = Client.find(attributes[:client_id])
    attributes[:number] = client.last_invoice_number + 1
    client.update_attributes(:last_invoice_number => client.last_invoice_number + 1)
  end
end

但是,当我调用 @client.invoices.build 时,attributes[:client_id] 设置。

发票的 client_id 如何以及何时初始化,我什么时候可以用它来初始化发票的 number?我可以将此逻辑放入模型中,还是必须将其放入 Controller 中?

最佳答案

生成一个向用户表添加 invoices_number 列的迁移。然后在 Invoice 模型中这样写:

class Invoice < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
  ...
end

这将在创建发票后自动增加用户的 invoices_count 属性。

关于ruby-on-rails - 在 Rails 中实例化对象时如何初始化属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3058787/

相关文章:

ruby-on-rails - Rspec不加载支持文件

ruby-on-rails - Liquid Ruby 模板引擎可以处理 Rails 表单吗?

ruby-on-rails - Heroku & Rails - Varnish 只是偶尔缓存

php - Laravel 模型返回 "Undefined property: stdClass::$name"

php - 遍历4个表时数据不一致

ruby-on-rails - 如何从 Google Container Engine 连接 Google Cloud SQL?

ruby-on-rails - rails : call method within model

ruby-on-rails - 更新属性 before_save 回调不保存额外的属性

text - 为什么 Storyboard不反射(reflect)我使用属性检查器面板设置为 UILabel 的文本属性?

javascript - 使用 jQuery 选择时如何获取元素的正常属性?