Rails вкратце Глава 2 Action Controller

Cody Fauser, James MacAulay, Edward Ocam,, “Rails in a nutshell Chapter 2. Action Controller”, public translation into Russian from English More about this translation.

See also 29 similar translations

Translate into another language.

Participants

Valeanna740 points
and_rew459 points
asplogika449 points
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5 6 7 8

Rails in a nutshell Chapter 2. Action Controller

Rails вкратце Глава 2 Action Controller

History of edits (Latest: asplogika 2 years, 6 months ago) §

Chapter 2. Action Controller

Глава 2 Action Controller

History of edits (Latest: asplogika 2 years, 6 months ago) §

Sessions

Сессии

History of edits (Latest: asplogika 2 years, 6 months ago) §

Maintaining state between a user's requests is a requirement of most of today's web applications. Tracking the state of an application's user between HTTP transactions has many important uses including personalization of content, tracking desired items for purchase in a shopping cart, knowing which user is currently logged in, and many others.

Сохранение состояния между запросами пользователя является требованием для большинства современных приложений. Сохранение состояния пользовательских настроек приложения между HTTP транзакциями может использоваться в таких важных задачах как персонализация содержимого, хранение желаемых записей для продажи в корзине покупок, запоминание авторизованного пользователя, и много других.

History of edits (Latest: asplogika 2 years, 6 months ago) §

Since HTTP is a stateless protocol by design, the server doesn't maintain any user information between requests. This means that it is up to the application framework or developer to provide session support.

Поскольку HTTP протокол по архитектуре не хранит состояние, сервер не получает никакой пользовательской информации между запросами. Это означает что поддержка сессий ложится на плечи разработчиков приложений.

History of edits (Latest: Valeanna 2 years, 6 months ago) §

Rails has complete support for sessions and makes maintaining user state easy through client or server based session stores. Rails supports several different session stores, allowing the developer to choose the type of session store that best meets the needs of the application.

Rails включает в себя полную поддержку сессий и облегчает хранение пользовательских данных с помощью клиент или сервер историю сессий. Rails поддерживает разные способы хранения сессий, позволяя разработчику выбирать лучший подходящий вариант для приложения.

History of edits (Latest: asplogika 2 years, 6 months ago) §

Using the session

Использование сессий

History of edits (Latest: asplogika 2 years, 6 months ago) §

The session is used like a hash and is available through the session accessor in controllers and views. To store an object in the session you assign a key in the session to the value you want to store:

Сессия используется также как и хеш таблица и доступ к ней предоставляется при помощи специального параметра в контроллере и в вьюшках. Для ого чтобы загрузить какой-либо объект в сессию вы присваиваете ключу в сессии значение которое хотите сохранить:

History of edits (Latest: asplogika 2 years, 6 months ago) §

session[:user_id] = @user.id

session[:user_id] = @user.id

History of edits (Latest: asplogika 2 years, 6 months ago) §

The session does not use indifferent access to hashes, unlike other parts of Rails such as params. This means that the keys "user_id" and :user_id are two different keys in the session, whereas they would be treated as the same key when accessing the params hash.

Сессия не предоставляет индиферентный доступ к хеш-таблице, в отличие от других частей фреймворка Rails, таких как параметры. Это означает что ключи "user_id" и :user_id являются двумя разными ключами сессии, хотя при доступе к хеш-таблице параметров они воспринимались бы как один.

History of edits (Latest: asplogika 2 years, 6 months ago) §

Above, just the user's id was stored in the session, but any object can be stored in the session:

Выше мы сохранили только идентификатор пользоваиеля в сессию, однако любой объект может быть сохранен в сессию.

History of edits (Latest: asplogika 2 years, 6 months ago) §

session[:user] = @user

session[:user] = @user

History of edits (Latest: asplogika 2 years, 6 months ago) §

Any object can be stored in the session because Rails automatically serializes and deserializes session data to and from the session store using Marshal.dump and Marshal.load. However, it is recommended to store only simple objects such as strings, and numbers in the session. Instead of storing the entire user in the session you would store the user's id and load the user on demand when needed during the request. Storing only lightweight, simple data in the session will help you avoid issues that might arise during deserialization of the stored objects from the session. Keeping a minimal amount of data in the session will also save on communication overhead for each request and response when you're using cookie session store.

Любой объект можно сохрянять в сессию потому что Rails автоматически серилизует и десерилизует данные сессии, используя Marshal.dump и Marshal.load. Однако рекомендуется сохранять в сессию только простые объекты, такие как строки и числа. Вместо сохранения всех пользвательских настроек лучше сохранить идентификатор пользователя в сессию и при необходимости запросом загружать остальную информацию. Хранение небольшого объема простой информации поможет избежать лишних ошибок, которые могут возникнуть при десериализации.Также поможет избежать перегрузки коммуникаций при сохранении сессии в куки.

History of edits (Latest: and_rew 2 years, 5 months ago) §
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5 6 7 8

© O'Reily. License: Creative Commons