Posts Tagged ‘foreign_key’

Ruby on Rails estendendo as migrações com helpers

Postado em 24 mar 2009
Categoria(s) Ruby on Rails

É muito comum termos nas migrações instruções sql para criar chaves estrangeiras e o rails não tem métodos para criar-las.

Por exemplo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class CreateGameTeams < ActiveRecord::Migration
  def self.up
    create_table :game_teams do |t|
      t.references :team, :null => false
      t.references :game, :null => false
      t.timestamps
    end
 
    execute "ALTER TABLE game_teams ADD CONSTRAINT fk_game_team_teams FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE CASCADE ON UPDATE
 CASCADE"
    execute "ALTER TABLE game_teams ADD CONSTRAINT fk_game_team_games FOREIGN KEY (game_id) REFERENCES games (id) ON DELETE CASCADE ON UPDATE
 CASCADE"
  end
 
  def self.down
    drop_table :game_teams
  end
end

Para simplificar mais as coisas, é possível criar helpers e estender as funcionalidades das migrações, é isso que será feito para criar um método que gera as chaves estrangeiras (foreign key).

Faça o seguinte:

No diretório lib do projeto crie o arquivo migration_helpers.rb com o conteúdo abaixo:

1
2
3
4
5
6
7
8
9
module MigrationHelpers
 
  def foreign_key(from_table, from_column, to_table)
    constraint_name = "fk_#{from_table}_#{from_column}"
 
    execute %{alter table #{from_table} add constraint #{constraint_name} foreign key (#{from_column}) references #{to_table}(id)}
  end
 
end

Agora é possível adicionar esse método a qualquer migração acrescentando as linhas a seguir no início do arquivo de migração:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require "migration_helpers"
 
class CreateGameTeams < ActiveRecord::Migration
 
  extend MigrationHelpers
 
  def self.up
    create_table :game_teams do |t|
      t.references :team, :null => false
      t.references :game, :null => false
      t.timestamps
    end
 
    foreign_key(:game_teams, :team_id, :teams)
    foreign_key(:game_teams, :game_id, :games)
  end
 
  def self.down
    drop_table :game_teams
  end
end

A linha require coloca a definição do módulo no código de migração e a linha extend adiciona os métodos do módulo MigrationHelpers à migração como métodos de classe.

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark

Ruby on Rails como fazer dois atributos da mesma classe apontarem para a mesma classe pai no ActiveRecord

Postado em 23 mar 2009
Categoria(s) Ruby on Rails

Hoje estava programando um sistema de menus, onde cada item de menu pode ter vários outros itens, não existindo limite de subníveis.

Para conseguir obter essa relação e associação no banco de dados criei dois models BackendMenu e BackendMenuNode, com as seguintes migrações:

BackendMenu:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CreateBackendMenus < ActiveRecord::Migration
  def self.up
    create_table :backend_menus do |t|
      t.string  :title,     :null => false
      t.string  :path,      :null => false
      t.integer :weight,    :null => false, :default => 0
      t.boolean :is_active, :null => false, :default => false
      t.boolean :is_root,   :null => false, :default => false
      t.timestamps
    end
  end
 
  def self.down
    drop_table :backend_menus
  end
end

BackendMenuNode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class CreateBackendMenuNodes < ActiveRecord::Migration
  def self.up
    create_table :backend_menu_nodes do |t|
      t.integer :root_id, :null => false
      t.integer :node_id, :null => false
      t.integer :weight,  :null => false, :default => 0
    end
 
    add_index(:backend_menu_nodes, [:root_id, :node_id], :unique => true)
    execute "ALTER TABLE backend_menu_nodes ADD CONSTRAINT fk_backend_menu_nodes_backend_menus_root FOREIGN KEY (root_id) REFERENCES backend_menus (id) ON DELETE CASCADE ON UPDATE CASCADE"
    execute "ALTER TABLE backend_menu_nodes ADD CONSTRAINT fk_backend_menu_nodes_backend_menus_node FOREIGN KEY (node_id) REFERENCES backend_menus (id) ON DELETE CASCADE ON UPDATE CASCADE"
  end
 
  def self.down
    drop_table :backend_menu_nodes
  end
end

Todos os itens de menu vão ficar cadastrados na tabela backend_menus e associação para descobrir os menus filhos será feito pela tabela backend_menu_nodes. A tabela backend_menu_nodes tem as colunas root_id que se referência ao pai e a coluna node_id que se referência aos menus filhos, desta forma um menu pode ter N itens.

Tanto a coluna root_id e node_id fazem referência a tabela backend_menus.

Para conseguir obter essa associação no ActiveRecord fiz o seguinte:

BackendMenu:

1
2
3
4
5
class BackendMenu < ActiveRecord::Base
  # associações
  has_many :nodes, :class_name => "BackendMenuNode", :foreign_key => "root_id"
  ...
end

BackendMenuNode:

1
2
3
4
5
6
class BackendMenuNode < ActiveRecord::Base
  # associações
  belongs_to :root, :class_name => "BackendMenu", :foreign_key => "root_id"
  belongs_to :node, :class_name => "BackendMenu", :foreign_key => "node_id"
  ...
end

Fazendo a relação acima eu consigo navegar pelo menu pai e os meus filhos.

Para imprimir o menu eu criei 3 helpers usando a recursividade:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
module BackendHelper
 
  # cria o menu do backend
  def menu(collection, class_name = "menu")
    content = content_tag :ul, :class => class_name do
      menu_items(collection)
    end
    content
  end
 
  # cria os items do menu
  def menu_items(collection)
    content = ""
    for item in collection
      if item.instance_of? BackendMenu
        content << item_nodes(item)
      else
        content << item_nodes(item.node)
      end
    end
    content
  end
 
  # cria os nós do item de menu
  def item_nodes(item)
    content = ""
    class_name = "leaf"
 
    if item.nodes.size > 0
      class_name = "collapsed"
      content << content_tag(:li, :class => class_name) do
        link_to(item.title, item.path) + menu(item.nodes, "menu hide")
      end
    else
      content << content_tag(:li, link_to(item.title, item.path), :class => class_name)
    end
    content
  end
 
end

No controlador eu faço o seguinte:

1
@backend_menus = BackendMenu.find :all, :conditions => { :is_root => true }, :order => 'weight'

Na view:

1
2
3
4
5
<!-- begin sidebar-left -->
<div id="sidebar-left">
  <%= menu(@backend_menus) %>
</div>
<!-- end sidebar-left -->

Se você quiser alguns menus de teste, usei a migração abaixo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
class AddBackendMenus < ActiveRecord::Migration
  def self.up
    BackendMenu.delete_all
 
    # criação dos menus pais
    BackendMenu.create(:title => 'Principal',
      :path => 'principal',
      :weight => 1,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Criar Conteúdo',
      :path => 'criar-conteudo',
      :weight => 2,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Gerenciamento de Conteúdo',
      :path => 'gerenciamento-de-conteudo',
      :weight => 3,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Site Construtor',
      :path => 'site-construtor',
      :weight => 4,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Site Configuração',
      :path => 'site-configuracao',
      :weight => 5,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Gerenciamento de Usuário',
      :path => 'gerenciamento-de-usuario',
      :weight => 6,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Relatórios',
      :path => 'relatorios',
      :weight => 7,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Ajuda',
      :path => 'ajuda',
      :weight => 8,
      :is_active => true,
      :is_root => true)
 
    # criação dos menus filhos
    BackendMenu.create(:title => 'Página',
      :path => 'criar-conteudo/pagina',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('criar-conteudo').id,
      :node_id => BackendMenu.find_by_path('criar-conteudo/pagina').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'História',
      :path => 'criar-conteudo/historia',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('criar-conteudo').id,
      :node_id => BackendMenu.find_by_path('criar-conteudo/historia').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Comentários',
      :path => 'gerenciamento-de-conteudo/comentarios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Ativos',
      :path => 'gerenciamento-de-conteudo/comentarios/ativos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/ativos').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Teste',
      :path => 'gerenciamento-de-conteudo/comentarios/ativos/teste',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/ativos').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/ativos/teste').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Inativos',
      :path => 'gerenciamento-de-conteudo/comentarios/inativos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/inativos').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Conteúdo',
      :path => 'gerenciamento-de-conteudo/conteudo',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/conteudo').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Tipos de Conteúdo',
      :path => 'gerenciamento-de-conteudo/tipos-de-conteudo',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/tipos-de-conteudo').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Publicação de RSS',
      :path => 'gerenciamento-de-conteudo/publicacao-de-rss',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/publicacao-de-rss').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'Blocos',
      :path => 'site-construtor/blocos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/blocos').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Formulários',
      :path => 'site-construtor/formularios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/formularios').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Menus',
      :path => 'site-construtor/menus',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/menus').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Módulos',
      :path => 'site-construtor/modulos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/modulos').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'temas',
      :path => 'site-construtor/temas',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/temas').id,
      :weight => 5)
 
    BackendMenu.create(:title => 'Tradução',
      :path => 'site-construtor/traducao',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/traducao').id,
      :weight => 6)
 
    BackendMenu.create(:title => 'Idiomas',
      :path => 'site-configuracao/idiomas',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/idiomas').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Logs e Alertas',
      :path => 'site-configuracao/logs-e-alertas',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/logs-e-alertas').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Manutenção do Site',
      :path => 'site-configuracao/manuencao-do-site',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/manuencao-do-site').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Ações',
      :path => 'site-configuracao/acoes',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/acoes').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'Regras de Acesso',
      :path => 'gerenciamento-de-usuario/regras-de-acesso',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/regras-de-acesso').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Permissões',
      :path => 'gerenciamento-de-usuario/permissoes',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/permissoes').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Regras',
      :path => 'gerenciamento-de-usuario/regras',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/regras').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Configurações de Usuários',
      :path => 'gerenciamento-de-usuario/configuracoes-de-usuarios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/configuracoes-de-usuarios').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'Usuários',
      :path => 'gerenciamento-de-usuario/usuarios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/usuarios').id,
      :weight => 5)
 
    BackendMenu.create(:title => 'Entrada de Logs',
      :path => 'relatorios/entrada-de-logs',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('relatorios').id,
      :node_id => BackendMenu.find_by_path('relatorios/entrada-de-logs').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Erros de Acesso Negado',
      :path => 'relatorios/erros-de-acesso-negado',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('relatorios').id,
      :node_id => BackendMenu.find_by_path('relatorios/erros-de-acesso-negado').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Status',
      :path => 'relatorios/status',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('relatorios').id,
      :node_id => BackendMenu.find_by_path('relatorios/status').id,
      :weight => 3)
  end
 
  def self.down
    BackendMenu.delete_all
  end
end

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark