Hello everyone!
I have 3 models:
=== 1 ==class Region < ActiveRecord::Base
has_many :districts
end
=== 2 ==class District < ActiveRecord::Base
belongs_to :region
has_many :suburbs
end
=== 3 ==class Suburb < ActiveRecord::Base
belongs_to :district
validates_numericality_of :region_id, :only_integer => true
end
In edit.rhtml for SuburbController I need to specify region_id.
There is no region_id in suburb model so first I added these lines to
it:
...
class Suburb < ActiveRecord::Base
belongs_to :district
attr_writer :region_id
def region_id
district.region_id if district
end
def region_id_before_type_cast
region_id
end
validates_numericality_of :region_id, :only_integer => true
end
...
Its all working now but it looks messy! And I need this functionality in
another few places. Obviously I dont want to put this rubbish into other
models!
I recently come across fields_for helper. So I commented out
"unnecessary" code in the model, put these into view:
...
<% fields_for :district, @suburb.district do |district_fields| %>
<%= district_fields.select :region_id, regions %>
<% end %>
...
And, guess what, I still need these damn methods in my model!
Why would I use fields_for then? I don''t know!
QUESTION 1: How can I apply fields_for in my case, so I do not need to
pollute my models? Or is there any other ways?
QUESTION 2: What is it all about this "_before_type_cast" method? I
mean
do I have to have it only to use validates_numericality_of? Can it be
created automatically?
Than you!
--
Posted via http://www.ruby-forum.com/.