Jesse Whitham
Jesse Whitham

Reputation: 824

How to validate data from a controller in a model?

I have data in my controller that is being received from another rails app and database (this has to be in the controller) I want to get this data so I can validate it in my model before allowing another step in a wizard (see my other question for some code examples)

My Problem is that I cannot directly grab this data from the controller in my model as this violates MVC.

My Question is how would I go about checking the controllers data in my Model?

Any help / steering in the right direction would be very useful. (also i cannot use a gem to do this)

Upvotes: 0

Views: 830

Answers (2)

Javier Amaya
Javier Amaya

Reputation: 1

I understand that the question was a while ago but for those who are still searching, I found the exact answer, how to pass the information from the controller to a model.

With this line everything is solved

var = request.env['target_model'].sudo().function_in_your_model(data) 

var is a variable in case you need to handle that data in the controller, target_model is the model where you want to send the data, function_in_your_model is the function where you are going to handle the data already in the model, and inside this function you send the data that you need.

Upvotes: 0

Daniel Vartanov
Daniel Vartanov

Reputation: 3267

At first, please be double double sure that you don't validate a model by data which it does not contain by itself. Model should validate its current state but not a way it came to this state (e.g. which user put a model to this state).

At second, you should never use controller methods in a model. If controller contains some business logic, extract that logic into a third class which will be used by both controller and model.

Moreover, you have a data in a controller and you have an access to the model, right?. Therefore, if you are in a controller method, for instance in a before filter or action, you could take that data and pass it to the model, like this:

def controller method
  hey_model.is_this_correct?(data)
end

If you say that that data must be checked after controller has responded to a request (for example, at the next wizard step, i.e. at the next request), then you definitely must store that value somewhere between requests.

This is the very point of stateless HTTP. No data is saved between requests until you explicitly do that. You could store your value in cookies or in database.

Upvotes: 1

Related Questions