我正在构建一个基本上遵循以下模式的发票应用程序:
Users < Clients < Projects < Invoices
现在为了为每个用户生成自动递增的发票编号,我将其放入我的 Invoice
中型号:
before_create :create_invoice_number
def create_invoice_number
val = @current_user.invoices.maximum(:number)
self.number = val + 1
end
但是,似乎无法从 Rails 的模型中访问 current_user 变量?
我该怎么做才能解决这个问题?
最佳答案
这是由于 Rails 中的关注点分离,并且是一个需要处理的有点棘手的问题。在 Rails 范例中,模型除了直接传递的内容外,不应该知道任何应用程序状态,因此大多数 Rails 编码人员会告诉您,任何需要了解 current_user 的模型都是代码味道。
也就是说,有三种方法可以做到这一点,每一种都“更正确”(或者至少我会这样认为)。
首先,尝试在发票中创建与用户的关联,并将发票链接到 Controller 中的用户:
class InvoicesController < ApplicationController
...
def create
@invoice = current_user.invoices.create(params[:invoice])
...
end
在你的模型中:
belongs_to :user
def create_invoice_number
self.user.invoices.maximum(:number) + 1
end
如果这不起作用,请在 Controller 中手动执行此操作。的确, Controller 应该始终尽可能瘦,但由于这显然是一个应用程序级别的问题,所以 Controller 是放置它的地方:
class InvoicesController < ApplicationController
...
def create
@invoice = Invoice.create(params[:invoice])
@invoice.update_attribute(:number, current_user.invoices.maximum(:number))
...
end
最后,如果您真的非常想连接 Controller 和模型,您可以使用 ActionController::Sweepers 来实现。 .它们不是为此目的而设计的,但肯定会为您完成工作。
关于ruby-on-rails - 从 Rails 模型中访问 current_user?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9400321/