Ruby 如何根据当前用户设置默认值?
我想根据创建它的用户设置一个默认值,我想知道如何做到这一点:Ruby 如何根据当前用户设置默认值?,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,我想根据创建它的用户设置一个默认值,我想知道如何做到这一点: class Item < ActiveRecord::Base belongs_to :invoice after_initialize :default_values ... private def default_values self.tax_rate = current_user.tax_rate || 0 end end 有人可以帮忙吗?您可以将属性传递给生成方法,以便在初
class Item < ActiveRecord::Base
belongs_to :invoice
after_initialize :default_values
...
private
def default_values
self.tax_rate = current_user.tax_rate || 0
end
end
有人可以帮忙吗?您可以将属性传递给
生成
方法,以便在初始化编辑控制器后删除:
def create
@invoice = Invoice.new(params[:invoice])
3.times { @invoice.items.build( :tax_rate => current_user.tax_rate }
...
end
@Tintin81被设置为发票的存取器,因此您只能在控制器中设置一次,您可以在项目中读取它,并且它不会存储在数据库中。这也将使您免于网页上的大量作业。@Tintin81我用一个解决方案完全重写了W答案,该解决方案删除了类中的所有耦合。
def create
@invoice = Invoice.new(params[:invoice])
3.times { @invoice.items.build( :tax_rate => current_user.tax_rate }
...
end