Is a Rails Model a normal ruby class that can be used to store state between different controller actions? No active-record and no-database at all

心已入冬 提交于 2019-12-25 02:38:06

问题


So I'm finally starting to get the hang of rails I think. :-) I need to step away from the standard Model (database) to: Controller to: View data exchange flow and stick in my own business logic non-database class as the Model. I have a few questions.

  1. I think of models as ORM to a database table. But are these models just regular java classes that can be used to store state? Because I need to use a basic ruby class that isn't going to be active-record based. I'm planning on using it to store state between different controller actions.

  2. I am aware we can't share controller instance variables (@two = 2) across other controller actions. BUT, if I create an instance of a regular non-database ruby model class in one controller method and mutate the object variable's attributes. How can I use that object reference in another controller method?

A nice thorough explanation to the above 2 questions would be soooo helpful to me that I'm going to throw a party! :-)

Thank you in advance!


回答1:


Models in Rails are like data access objects, so either you would have a database backing your model or an api supporting persistence. Models are regular classes which holds state, but only for the lifetime of the current request. So your data will be gone once the request finishes by rendering a view or redirecting to another page.

You could store your model object in the session, in a cookie or in the browser's local storage, which would not require a database backend. Depending on the needs of your application it may work out for you.



来源:https://stackoverflow.com/questions/22442117/is-a-rails-model-a-normal-ruby-class-that-can-be-used-to-store-state-between-dif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!