Ruby on Rails ActiveRecord como excluir registros dependentes e arquivos anexados com o Paperclip

Digamos que você tenha uma mensagem, e essa mensagem possa ter várias fotos e vídeos relacionadas com ela.

Com o model message.rb da forma abaixo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Message < ActiveRecord::Base
  # associações
  belongs_to :user
  has_many :photos
  has_many :videos
 
  # validações
  # presença
  validates_presence_of :title
  validates_presence_of :content
 
  # tamanho máximo
  validates_length_of :title, :maximum => 255
end

Se você usar Paperclip para anexar as fotos e vídeos, quando você apagar uma mensagem os arquivos de fotos e vídeos iram continuar a existir no disco rígido.

Para forçar que todas as relações filhas sejam apagadas quando você excluir a mensagem, você deve adicionar :dependent => :destroy na declaração has_many, ficando assim:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Message < ActiveRecord::Base
  # associações
  belongs_to :user
  has_many :photos, :dependent => :destroy
  has_many :videos, :dependent => :destroy
 
  # validações
  # presença
  validates_presence_of :title
  validates_presence_of :content
 
  # tamanho máximo
  validates_length_of :title, :maximum => 255
end

Essa alteração força para que todos os dependentes sejam excluídos.

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

Posted in Ruby on Rails at junho 10th, 2009. No Comments.

Ruby on Rails debug para descobrir todos os métodos públicos de um objeto

No Ruby existe o método public_methods ele retorna todos os métodos públicos de um objeto. Você pode usar ele junto com o método debug.

Exemplo:

1
2
3
4
5
...
<% if @drafts.size > 0 %>
  <% @drafts.each do |draft| %>
  <%= debug(draft.public_methods) %>
...

Isso irá produzir a saída 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
--- 
- save_without_validation
- destroy_without_transactions
- validate_associated_records_for_photos
- silence_stream
- reject_new_nested_attributes_procs
- save_with_dirty!
- extend_with_included_modules_from
- marked_for_destruction?
- update_attributes!
- autosave_associated_records_for_user
- methods
- send
- has_attribute?
- destroy_without_callbacks
- connection_handler
- taint
- to_enum
- instance_variable_defined?
- encode64
- write_attribute
- after_validation_on_create
- save_with_transactions
- connection
- table_name_prefix
- write_attribute_without_dirty
- require_or_load
- save_without_dirty!
- increment!
- validate_associated_records_for_user
- reload_with_dirty
- singleton_methods
- instance_eval
- time_zone_aware_attributes
- changed?
- decrement
- schema_format
- debugger
- returning
- lock!
- valid?
- enum_for
- subclasses_of
- metaclass
- before_validation_on_update
- nil?
- to_xml
- reload
- decode64
- before_update
- videos
- unserializable_attribute?
- reload_without_dirty
- protected_methods
- instance_exec
- readonly?
- unserialize_attribute
- from_json
- default_timezone
- tainted?
- videos=
- before_save
- breakpoint
- changed
- rollback_active_record_state!
- untaint
- instance_of?
- with_options
- after_validation_on_update
- equal?
- save_without_transactions
- table_name_suffix
- suppress
- require_association
- taguri
- readonly!
- decode_b
- decrement!
- respond_to_without_attributes?
- column_for_attribute
- after_update
- photos
- blank?
- hash
- private_methods
- daemonize
- taguri=
- toggle
- locking_enabled?
- attribute_names
- `
- after_save
- save!
- photos=
- timestamped_migrations
- partial_updates?
- to_json
- changes
- kind_of?
- reload_with_autosave_associations
- freeze
- store_full_sti_class?
- eql?
- to_yaml_style
- present?
- instance_values
- id
- destroy_without_lock
- public_methods
- method_missing
- id=
- valid_with_callbacks?
- save_with_transactions!
- is_a?
- require
- becomes
- pluralize_table_names
- video_ids
- require_library_or_gem
- tap
- load_with_new_constant_marking
- dclone
- cache_key
- _delete
- attributes_before_type_cast
- type
- instance_variable_names
- toggle!
- save
- to_yaml
- video_ids=
- to_param
- transaction
- instance_variables
- to_yaml_properties
- loaded_user?
- query_attribute
- clear_aggregation_cache
- __id__
- require_dependency
- save_with_validation!
- from_xml
- frozen?
- valid_without_callbacks?
- store_full_sti_class
- acts_like?
- record_timestamps
- save_with_dirty
- save_without_transactions!
- set_user_target
- to_a
- reload_without_autosave_associations
- before_destroy
- display
- respond_to?
- autosave_associated_records_for_videos
- attribute_types_cached_by_default
- method
- attribute_for_inspect
- class
- copy_instance_variables_from
- id_before_type_cast
- before_validation
- to_query
- photo_ids
- configurations
- destroy_with_transactions
- enable_warnings
- instance_variable_get
- invalid?
- clear_association_cache
- __send__
- save_without_validation!
- default_scoping
- ==
- before_create
- ===
- extend
- save_without_dirty
- build_user
- photo_ids=
- to_s
- unloadable
- run_callbacks
- update_attribute
- after_destroy
- update_attributes
- mark_for_destruction
- duplicable?
- colorize_logging
- validate_associated_records_for_videos
- skip_time_zone_conversion_for_attributes
- silence_warnings
- attributes
- increment
- b64encode
- read_attribute_before_type_cast
- clone
- after_validation
- save_with_validation
- errors
- with_transaction_returning_status
- user
- primary_key_prefix_type
- autosave_associated_records_for_photos
- silence_stderr
- =~
- instance_variable_set
- read_attribute
- attributes=
- try
- extended_by
- new_record?
- after_create
- user=
- create_user
- destroy_with_callbacks
- destroy
- attribute_present?
- include_root_in_json
- inspect
- "[]"
- class_eval
- lock_optimistically
- partial_updates
- delete
- logger
- "[]="
- dup
- object_id
- remove_subclasses_of
- quoted_id
- before_validation_on_create

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

Posted in Ruby on Rails at junho 10th, 2009. No Comments.

Ruby on Rails debugando variáveis

No Ruby existe o método debug, com ele você pode debugar uma variável e visualizar todos os parâmetros.

Exemplo:

1
2
3
4
5
...
<% if @drafts.size > 0 %>
  <% @drafts.each do |draft| %>
    <%= debug(draft) %>
...

Esse exemplo irá gerar a seguinte saída:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
--- !ruby/object:Message 
attributes: 
  step: "1"
  created_at: 2009-06-04 20:11:21
  title: Legal
  updated_at: 2009-06-10 18:25:51
  id: "1"
  user_id: "1"
  content: |-
    <p>Vamos testar</p>
    <p>Legal para carambaaa</p>
    <p>Vamos atualizar as informa&ccedil;&otilde;es.....</p>
  send_date: 
attributes_cache: {}

Essa é uma dica simples, mas que pode ajudar bastante.

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

Posted in Ruby on Rails at junho 10th, 2009. No Comments.

Ruby on Rails time_ago_in_words

Gosto muito de algumas coisas simples do Rails, o helper time_ago_in_words é uma delas, serve para escrever a quanto tempo ocorreu a partir da data atual.

Por exemplo:

1
2
3
time_ago_in_words(3.minutes.from_now)       # => 3 minutes
time_ago_in_words(Time.now - 15.hours)      # => 15 hours
time_ago_in_words(Time.now)                 # => less than a minute

Outro exemplo:

1
2
3
4
5
6
<ol class="timeline">
  <li> 
    <span class="title"><%= draft.title %></span>
    <span class="updated_at"><%= time_ago_in_words(draft.updated_at) %> ago</span>
  </li>
</ol>

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

Posted in Ruby on Rails at junho 5th, 2009. No Comments.

Comunidade Ruby on Rails Brasil

Visando contribuir e ampliar os horizontes da comunidade Ruby on Rails no Brasil, eu criei o site http://railsbrasil.ning.com.

Caso você tenha interesse, faça o seu cadastro, participe, colabore e vamos todos juntos divulgar esse maravilhoso framework.

Posted in Ruby on Rails at junho 2nd, 2009. No Comments.

 Assinar RSS Feed