Руководства Ruby On Rails: Ассоциации в Active Record | Participants
|
- Statistics
- Participants
- Translate into Russian
- Translation result
- Translated in draft, editing and proof-reading required.
If you do not want to register an account, you can sign in with OpenID.
Ruby on Rails Guides: Active Record Associations | Руководства Ruby On Rails: Ассоциации в Active Record | |
A Guide to Active Record Associations | — для единообразия наверно тут тоже надо "ассоциации" использовать. — GremL1N | |
This guide covers the association features of Active Record. By referring to this guide, you will be able to: | Это руководство описывает особенности ассоциаций в Active Record. Прочитав данное руководство вы сможете: | |
* | · объявлять ассоциации между моделями Active Record; | |
Declare associations between Active Record models | Comment was deleted — понимать различные типы — Mechiko | |
Understand the various types of Active Record associations | · использовать методы, добавленные в вашу модель путем создания ассоциаций. | |
Use the methods added to your models by creating associations | · использовать методы, добавляемые в модель при создании ассоциации. | |
1. Why Associations? | ||
Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this: | Зачем нужны ассоциации между моделями? Они облегчают и упрощают ваш код. Простой пример приложения Rails: модель для заказчиков и модель для заказов. У каждого заказчика может быть много заказов. Без ассоциаций объявление модели может выглядеть так: | — Зачем нужны ассоциативные связи между моделями? Они делают ваш код проще и легче. Простой пример приложения Rails: модель заказчиков и модель заказов. У каждого заказчика может быть много заказов. Без ассоциативных связей модель можно задать таким образом: — Mechiko Почему, Потому что, Для примера - затрудняют чтение, они лезут из прямого перевода. Лучше может избегать этих словосочетаний. — Mechiko |
class Customer < ActiveRecord::Base | ||
class Order < ActiveRecord::Base | ||
Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this: | Теперь предположим, что мы хотим добавить новый заказ для существующего клиента. Потребуется примерно такой код: | |
@order = Order.create(:order_date => Time.now, :customer_id => @customer.id) | @order = Order.create(:order_date => Time.now, :customer_id => @customer.id) | |
Or consider deleting a customer, and ensuring that all of its orders get deleted as well: | Или, скажем, удаление заказчика с гарантированным удалением всех его заказов: | |
@orders = Order.find_by_customer_id(@customer.id) | @orders = Order.find_by_customer_id(@customer.id) @orders.each do |order| order.destroy end @customer.destroy | |
With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders: | Используя отношения Active Record, мы ускорим большую часть работы - объявив для Rails ассоциативную связь между двумя моделями. Пересмотрим код настройки клиентов и заказов: | |
class Customer < ActiveRecord::Base | class Customer < ActiveRecord::Base has_many :orders | |
class Order < ActiveRecord::Base | class Order < ActiveRecord::Base belongs_to :customer | |
With this change, creating a new order for a particular customer is easier: | Теперь создание нового заказа для отдельного клиента стало проще: | |
@order = @customer.orders.create(:order_date => Time.now) | @order = @customer.orders.create(:order_date => Time.now) | |
Deleting a customer and all of its orders is much easier: | Удаление покупателя и всех его заказов стало намного проще: | — test — solid |
@customer.destroy | ||
To learn more about the different types of associations, read the next section of this Guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails. | Для изучения различных типов ассоциаций, прочитайте следующий раздел этого руководства. Также в руководстве вы найдете несколько советов и трюков для работы с ассоциациями и полный справочник по методам и параметрам ассоциациативных связей в Rails. |

— я не люблю рано вставать — Kissa
— связи, соединения, ассоциации -- как лучше? — and_rew
В "Путь Rails" переведено как "отношение" — and_rew
— отношения это больше relation а Associations это и есть Ассоциации — Mechiko