bdeonovic
bdeonovic

Reputation: 4220

Ruby: Variables scope questions

Hey Rails newbie here.

I used to have a lot of stuff going on in one of my controllers. Someone told me that its good practice to have "fat models and thin controllers" So I was moving some things over to the model.

In my controller's show method I used to have some @ variables that I would use in my view. Now I have those variables in a method in my model. Will I still be able to access those in my view? If so do I have to make any adjustments?

Thanks

Upvotes: 2

Views: 304

Answers (2)

Vlad Khomich
Vlad Khomich

Reputation: 5880

The common practice is to define the variables of this kind in controllers:

@object = Model.new

to later use it in form_for or something like that. Some people use Model.new directly in views instead. That's somewhat unusual but still makes sense, especially knowing that Rails just loops through all of the instance variables in your controller every time to make them available in your views

Upvotes: 0

mikej
mikej

Reputation: 66263

You will have to create an instance of your model in the controller as an @ variable. You can then call the methods from that inside the view.

e.g. imagine you used to have some long bunch of logic in your controller which calculated a credit score for a customer culminating in

@credit_score = credit_score

and you've now moved this into a credit_score method on the Customer model.

You now just need

@customer = Customer.find...

in the controller

and you can the use <%= @customer.credit_score %> within the view.

This is what people mean by fat models and thin controllers. If you'd like some more advice then it's best to update the question with some specifics from your app.

Upvotes: 5

Related Questions