Руководство по Ruby on Rails: Active Record: базовые ассоциации

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

See also 32 similar translations

Translate into another language.

Participants

yukiki1524 points
dymdym48 points
lightalloy36 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 next untranslated

Ruby on Rails Guides: Active Record: Association basics

Руководство по Ruby on Rails: Active Record: базовые ассоциации

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

— этот текст уже переводится под другим именем: http://translated.by/you/ruby-on-rail... and_rew

A Guide to Active Record Associations
=====================================

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

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

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: yukiki 1 year, 11 months ago) §

* Declare associations between Active Record models
* Understand the various types of Active Record associations
* Use the methods added to your models by creating associations

* Описывать отношения между моделями Active Record.
* Понимать различные типы отношений Active Record.
* Использовать методы моделей, появляющиеся в результате создания отношений.

History of edits (Latest: yukiki 1 year, 11 months ago) §

== Why Associations?

== Почему ассоциации?

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

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-приложение, включающее модели Customer (покупатели) и Order (заказы). У каждого покупателя может быть много заказов. Без отношений модели буду выглядеть следующим образом:

History of edits (Latest: yukiki 1 year, 11 months ago) §

[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
end

[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
end

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

class Order < ActiveRecord::Base
end
-------------------------------------------------------

class Order < ActiveRecord::Base
end

History of edits (Latest: dymdym 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: dymdym 2 years, 7 months ago) §

[source, ruby]
-------------------------------------------------------
@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
-------------------------------------------------------

[source, ruby]
-------------------------------------------------------
@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
-------------------------------------------------------

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

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

Или мы решаем удалить пользователя, равно как и все его заказы:

History of edits (Latest: yukiki 1 year, 11 months ago) §

[source, ruby]
-------------------------------------------------------
@orders = Order.find_by_customer_id(@customer.id)
@orders.each do |order|
order.destroy
end
@customer.destroy
-------------------------------------------------------

[source, ruby]
-------------------------------------------------------
@orders = Order.find_by_customer_id(@customer.id)
@orders.each do |order|
order.destroy
end
@customer.destroy
-------------------------------------------------------

History of edits (Latest: yukiki 1 year, 11 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: yukiki 1 year, 11 months ago) §

[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
has_many :orders
end

[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
has_many :orders
end

History of edits (Latest: yukiki 1 year, 11 months ago) §

class Order < ActiveRecord::Base
belongs_to :customer
end
-------------------------------------------------------

class Order < ActiveRecord::Base
belongs_to :customer
end
-------------------------------------------------------

History of edits (Latest: yukiki 1 year, 11 months ago) §
Pages: ← previous Ctrl next next untranslated