如何在另一个模型中为一个模型设置变量?

时间:2020-09-09 02:45:59

标签: ruby-on-rails

因此,基本上我想使用一个称为“收费”的模型来生成发票。

class Charge < ApplicationRecord
 belongs_to :client
 
 def invoice
  Receipts::Invoice.new(
    id: id,
    issue_date: Date.today,
    due_date: Date.today + 30,
    status: "<b><color rgb='#5eba7d'>PAID</color></b>",
    bill_to: [
      "#{client.full_name}",
      nil,
      "mail@example.com"
    ],
    company: {
      name: "Teste LTDA",
      address: "Avenida Paulista, 648, apto 503 bloco 01",
      email: "teste@teste.com",
    },
    line_items: [
      ["<b>Item</b>", "<b>Unit Cost</b>", "<b>Quantity</b>", "<b>Amount</b>"],
      ["GoRails Subscription", "$19.00", "1", "$19.00"],
      [nil, nil, "Subtotal", "$19.00"],
      [nil, nil, "Tax Rate", "0%"],
      [nil, nil, "Total", "$19.00"],
    ],
  )
 end
end

通过这种方式,我可以访问客户端信息,例如“ client.full_name”。但是我的客户模型链接到我的“地址”模型,如下所示:

class Address < ApplicationRecord
  belongs_to :client, optional: true
end

通过这种方式,我认为可以在“收费”模型中设置类似以下内容:

@address = Address.find_by(client_id: client_id)

但是当我尝试在show action中生成发票时,它表明它没有client_id。因此,我尝试在模型中编写如下内容:

@address = Address.find(3)

但是在这种情况下,当我尝试在我的方法中恢复街道信息时,它显示:“ nil:NilClass的未定义方法'street'”

我该怎么办?如何在模型中获取此信息?

1 个答案:

答案 0 :(得分:1)

处理此问题的正确方法是创建一个indirect association-而不是直接通过id查询。

class Charge < ApplicationRecord
  belongs_to :client
  has_one :address, through: :client
end

class Client < ApplicationRecord
  has_one :address
end

发票的生成是否属于该模型也很成问题,因为它应该是Receipts::Invoice上的工厂方法(创建实例的类方法)还是以其他方式完成,例如服务对象。