Wednesday, April 9, 2008

ActiveScaffold - Helpers for columns with same name overwrite each other - FIX

Really quick one today. I was working on my ActiveScaffold project, and came across the following problem:
My Events table has a column called schools, and so does my Schools table. For the Events, I needed a dropdown box listing all schools...while for Schools, I needed a text box to show up to type in the name of the school. Since textboxes are the default for activescaffold, I shouldn't need to do anything with schools in it, however, when I wrote a form override for Events in event_helper.rb to give it a dropdown box...the dropdown showed up in Schools also. So first, I tried doing a form override in the school_helper.rb. No luck, the event helper method has the same name, and overrides whatever method I put in school with the same name. So to fix it, I removed my helper methods from the event and school helpers. In application_helper.rb, I made a function with the same name as the form override function I had been trying to use, and then used an if to determine which model the helper was being called from. Here is the code:


# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

#hack to make activescaffold form overrides work when 2 models have a field that is the same name
def school_form_column(record, input_name)
if record.class.name == "Event"
select_tag input_name, options_for_select(aschools, selected = record.school)
else #record.class.name =="School"
text_field :record, :school, :name => input_name
end
end

private
#used in case of Event
def aschools
@schools = School.find(:all, :order => 'school')
@schooloptions = Hash.new
for school in @schools
@schooloptions[school.school] = school.abbrv
end
@schooloptions = @schooloptions.sort.each { |e| puts "#{e[0]} => #{e[1]}" }

end

end



Me: 2
ActiveScaffold: 0

Done.

7 comments:

icmgr said...

An easier fix is to comment out the following line from application.rb like this:
#helper: all

Gabriel Sobrinho said...

I have the same problem.

But, my application have 18 entities and i cant use the "if fix".

I tryed to comment the line (commented by icmgr) but doesnt fixed.

Have another solution?

Tks

rledge21 said...

g. sobrinho: I would recommend a switch case statement

Gabriel Sobrinho said...

rledge21, it this a bug of Rails?

rledge21 said...

No, its a bug of ActiveScaffold. From what I have seen, a lot of experienced Rails'ers are kind of critical of ActiveScaffold, it doesn't fit in with the 'Rails Way'.

Carlos Werberich said...

Good and simple idea. This behaviour should be fixed from ActiveScaffold.
Thanks for sharing this idea.

muebles baratos said...

I totally match with everything you've written.