Связь многие ко многим без танцев с бубном! | Participants
|
- Statistics
- Participants
- Translate into Russian
- Translation result
- 17% translated in draft.
If you do not want to register an account, you can sign in with OpenID.
Many-to-many Dance-off! | ||
I've noticed there's a bit of confusion about the differences between the two ways to create many-to-many relationships using Rails associations. That confusion is understandable, since has_many :through is still pretty new there isn't much written about it. has_and_belongs_to_many is the old, established player and most stuff out there assumes that's what you use for a many-to-many relationship. In fact, a lot of people don't seem to grasp that there is a difference at all! | Я заметил, что есть небольшая путаница между двумя различными путями создания отношений "многие ко многим" используя ассоциации в Rails. Причина путаницы в том, что метод has_many :throught еще достаточно нов и о нем мало что написано. Метод has_and_belongs_to_many старый, устоявшийся инструмент и большинство | |
As we all learned from watching classic movies, the best way to tell the difference between two prospective choices is to have a dance-off. You get to see everyone's moves (which of course are an accurate reflection of inner character), nobody has to die, and the hummable tune makes it a shoe-in for an Oscar nomination. Well, it's either that or do one of those boring "compare and contrast" essays they taught us about in sixth grade English class. | ||
So who are the players we have to choose between? Let's take a quick look at them before the music starts and we get to see their moves. | ||
Join Table: Simple Associations | ||
Table: | ||
create_table "dancers_movies", :id => false do |t| | ||
t.column "dancer_id", :integer, :null => false | ||
t.column "movie_id", :integer, :null => false | ||
end | ||
Models: | ||
class Dancer < ActiveRecord::Base | ||
has_and_belongs_to_many :movies | ||
end | ||
class Movie < ActiveRecord::Base | ||
has_and_belongs_to_many :dancers | ||
end | ||
has_and_belongs_to_many associations are simple to set up. The join table has only foreign keys for the models being joined - no primary key or other attributes. (Other attributes were supported using push_with_attributes for a while, but that feature has been deprecated.) There is no model class for the join table. | ||
Join Model: Rich Associations | ||
Table: | ||
create_table "appearances", do |t| | ||
t.column "dancer_id", :integer, :null => false | ||
t.column "movie_id", :integer, :null => false | ||
t.column "character_name", :string | ||
t.column "dance_numbers", :integer | ||
end | ||
Models: | ||
class Appearance < ActiveRecord::Base |
