Rails:控制器实例变量如何工作 [英] Rails: How does controller instance variables work

查看:39
本文介绍了Rails:控制器实例变量如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,作为 Rails 和 Web 开发的初学者,我不知道如何表达我的问题,所以请随时改写.

Good Morning, As a beginner to both Rails and web development, I don't know how to articulate my question so please feel free to rephrase.

我读到 Rails 中的视图通过控制器的实例变量获取要显示的数据.我还读到为每个请求创建了一个控制器实例.所以我的问题是,假设多个同时请求,rails 如何知道哪个视图获取哪些值?由于每个控制器实例都是共享的,那么将值放在实例变量中是否明智?

I read that that a view in Rails gets the data to display via instance variables from the controller. I also read that an instance of the controller is created for each request. So my question is how does rails know which view gets which values assuming multiple simultaneuos requests? Since each controller instance is shared, is it wise to put values in the instance variables?

推荐答案

答案就在你的问题里,我的朋友:

The answer is in your question my friend :

每次请求都会创建一个控制器实例.因此,每个请求——IE 浏览器中的每个用户,每个 ajax 请求等等——都会实例化一个新的控制器.MVC 中的规则是,控制器对于每个请求都应该是无状态的.这就是你的答案.

An intance of the controller is created on every request. Therefore, each request - IE each user browsing in firefox, each ajax request etc... - will instanciate a new controller. It's the rule in MVC that says a controller should be stateless for each request. That's your answer.

这篇关于Rails:控制器实例变量如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆