一个模型方法从以下逻辑开始:
def calculate_vat
if self.country.blank?
flash[:danger] = "Please select country first"
redirect_to edit_organization_path(self) and return
end
if ["BE", "CZ", "ES", "LV", "LT"].include? self.country
return 0.21
elsif etc. for other countries.
end
end
这在模型方法中是不可能的吗?在控制器中,使用@organization.model_method
调用模型方法。在开发过程中产生以下错误:undefined local variable or method 'flash' for #<Organization:0x00000007298a68>
.
更新:我现在明白了,在模型方法中不可能使用flash和重定向。但是如何解决这个问题呢?只有一组特定的用户会使用这种模型方法;所以我不想让所有用户都需要country
。定制需求似乎是不可能的,因为没有模型变量作为验证的基础,这是用户是否会到达某些结帐页面的问题。
最好的解决方案可能是定义一个私有控制器方法,在calculate_vat
被调用之前从控制器内部调用?
这毫无意义。
在方法被调用后,在控制器的动作中触发所需的flash消息,就这样。
实际上,您在model_method
中所做的所有都是纯粹的验证,因此只需正确定义它:
validates :country, presence: true