Руководства Ruby On Rails: Ассоциации в Active Record

Frederick Cheung, Mike Gunderloy, Emilio Tagua, Heiko Webers, Tore Darell, Jeff Dean, “Ruby on Rails Guides: Active Record Associations”, public translation into Russian from English More about this translation.

See also 32 similar translations

Translate into another language.

Participants

and_rew7189 points
satone667398 points
lightalloy108 points
And others...
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

Ruby on Rails Guides: Active Record Associations

Руководства Ruby On Rails: Ассоциации в Active Record

History of edits (Latest: and_rew 2 years, 1 month ago) §

— я не люблю рано вставать Kissa

— связи, соединения, ассоциации -- как лучше? and_rew

В "Путь Rails" переведено как "отношение" and_rew

— отношения это больше relation а Associations это и есть Ассоциации Mechiko

A Guide to Active Record Associations

Руководство по ассоциациям в Active Record

History of edits (Latest: and_rew 2 years ago) §

— для единообразия наверно тут тоже надо "ассоциации" использовать. GremL1N

This guide covers the association features of Active Record. By referring to this guide, you will be able to:

Это руководство описывает особенности ассоциаций в Active Record. Прочитав данное руководство вы сможете:

History of edits (Latest: and_rew 2 years, 1 month ago) §

*

· объявлять ассоциации между моделями Active Record;

History of edits (Latest: and_rew 2 years, 1 month ago) §

Declare associations between Active Record models
*

· понимать различия между типами отношений;

History of edits (Latest: and_rew 2 years, 7 months ago) §

Comment was deleted

— понимать различные типы  Mechiko

Understand the various types of Active Record associations
*

· использовать методы, добавленные в вашу модель путем создания ассоциаций.

History of edits (Latest: and_rew 2 years, 1 month ago) §

Use the methods added to your models by creating associations

· использовать методы, добавляемые в модель при создании ассоциации.

History of edits (Latest: and_rew 2 years, 1 month ago) §

— использовать методы добавляемые через создание ассоциаций Mechiko

— исправляйте сразу в тексте. В следующем абзаце - принятая редакция: "Почему ассоциации" and_rew

1. Why Associations?

1. Почему ассоциации?

Unapproved edits (Latest: solid 3 years, 5 months ago) §

— Почувствуйте разницу между фразами: Какое вы имеете отношение к данному делу? или, скажем: Что у вас с этим ассоциируется?  Mechiko

Введя термин Отношения получим в итоге путаницу, подобную: какое имеет отношение данное отношение к данной модели :) Mechiko

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: модель для заказчиков и модель для заказов. У каждого заказчика может быть много заказов. Без ассоциаций объявление модели может выглядеть так:

History of edits (Latest: and_rew 2 years, 1 month ago) §

— Зачем нужны ассоциативные связи между моделями? Они делают ваш код проще и легче. Простой пример приложения Rails: модель заказчиков и модель заказов. У каждого заказчика может быть много заказов. Без ассоциативных связей модель можно задать таким образом: Mechiko

Почему, Потому что, Для примера - затрудняют чтение, они лезут из прямого перевода. Лучше может избегать этих словосочетаний. Mechiko

class Customer < ActiveRecord::Base
end

class Customer < ActiveRecord::Base
end

History of edits (Latest: and_rew 2 years, 7 months ago) §

class Order < ActiveRecord::Base
end

class Order < ActiveRecord::Base
end

History of edits (Latest: and_rew 2 years, 7 months ago) §

Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:

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

History of edits (Latest: Mechiko 2 years, 1 month ago) §

@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)

@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)

History of edits (Latest: satone667 3 years, 5 months ago) §

Or consider deleting a customer, and ensuring that all of its orders get deleted as well:

Или, скажем, удаление заказчика с гарантированным удалением всех его заказов:

History of edits (Latest: Mechiko 2 years, 1 month ago) §

@orders = Order.find_by_customer_id(@customer.id)
@orders.each do |order|
order.destroy
end
@customer.destroy

@orders = Order.find_by_customer_id(@customer.id) @orders.each do |order| order.destroy end @customer.destroy

History of edits (Latest: satone667 3 years, 5 months ago) §

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 ассоциативную связь между двумя моделями. Пересмотрим код настройки клиентов и заказов:

History of edits (Latest: Mechiko 2 years, 1 month ago) §

class Customer < ActiveRecord::Base
has_many :orders
end

class Customer < ActiveRecord::Base has_many :orders
end

History of edits (Latest: and_rew 2 years, 7 months ago) §

class Order < ActiveRecord::Base
belongs_to :customer
end

class Order < ActiveRecord::Base belongs_to :customer
end

History of edits (Latest: and_rew 2 years, 7 months ago) §

With this change, creating a new order for a particular customer is easier:

Теперь создание нового заказа для отдельного клиента стало проще:

History of edits (Latest: satone667 3 years, 5 months ago) §

@order = @customer.orders.create(:order_date => Time.now)

@order = @customer.orders.create(:order_date => Time.now)

History of edits (Latest: satone667 3 years, 5 months ago) §

Deleting a customer and all of its orders is much easier:

Удаление покупателя и всех его заказов стало намного проще:

History of edits (Latest: satone667 3 years, 5 months ago) §

— test solid

@customer.destroy

@customer.destroy

History of edits (Latest: satone667 3 years, 5 months ago) §

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.
2. The Types of Associations

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

History of edits (Latest: and_rew 2 years, 1 month ago) §
Pages: ← previous Ctrl next