开发者

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. Wil开发者_运维问答l I still be able to access those in my view? If so do I have to make any adjustments?

Thanks


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜