0

A model method starts with the following logic:

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

Is this not possible within a model method? In the controller, the model method gets called upon using @organization.model_method. It produces the following error in development: undefined local variable or method 'flash' for #<Organization:0x00000007298a68>.

Update: I understand now that it's impossible to use flash and redirect in model method. But how to solve this? Only a specific group of users will ever deal with this model method; so I don't want to make country required for all users. A custom requirement seems impossible because there are no model variables upon which to base such a validation, it's a matter whether a user will ever get to certain checkout pages.

Would the best solution perhaps be to define a private controller method that is called upon from inside the controller just before calculate_vat is called upon?

Marty
  • 2,132
  • 4
  • 21
  • 47

1 Answers1

0

This is senseless.

Fire the desired flash message in the controller's action after the method is being called and that's it.

Actually, everything you do in the model_method is a pure validation, so just define it properly:

validates :country, presence: true
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • How would you suggest dealing with the following: at various places in multiple controllers I call upon this model method. *Before*, calling this model method, the lines with the flash message need to be executed. Should I now add these lines everywhere in the controllers where I call upon this model method? That doesn't sound DRY to me. I can't use it as a `before_action` on the controller methods either, because there are `if` conditions, which differ between controller methods, that determine whether the model method will be called upon inside the controller methods or not. – Marty Sep 20 '15 at 10:34
  • A general validation for country is not desirable. Only when this model method is called upon, country is necessary. There will be many users who will never call upon this model method. – Marty Sep 20 '15 at 10:37
  • you can define conditional validation – Andrey Deineko Sep 20 '15 at 10:37
  • please update the question with complete `model_method` – Andrey Deineko Sep 20 '15 at 10:38
  • Using a private controller method, that is called upon in the different controller methods works – Marty Sep 20 '15 at 10:57