Generic 'save' function for multiple objects?


#1

I’ve been working with developing a few rails/mysql applications to
replace some rather shoddy access databases that are currently in use
here.

It’s going well but I ran into one area that I’m curious if there is a
way to improve. Basically the database has several instances of
Many-to-Many relationships to handle different things.

At present each of these has a seperate “add” function that looks like
this:


def add_entry
@entry = Entry.new(params[:entry])
@entry.item_id = params[:id]
if @entry.save
flash[:notice] = “Record updated.”
redirect_to :action => “show”, :id => params[:id]
else
flash[:notice] = “Error: failed to add entry!”
redirect_to :action => “show”, :id => params[:id]
end
end
end

Each is virtually identical except one is using say an entry object and
the next is using a post object. Is there a way to just build a more
generic function that would take over this process so I could just pass
it and item and it would take care of saving it properly? Is it worth
bothering with?

The Agile web development book stresses not repeating the same code over
and over and I’m up to 3 instances of this same basic function, I’m not
sure there is a way to avoid it and it’s not that big of a deal. I did
a bit of searching and really couldn’t find something that addressed
this.

Kevin Kolk


#2

Kevin Kolk wrote:

end

end
end

Each is virtually identical except one is using say an entry object and
the next is using a post object. Is there a way to just build a more
generic function that would take over this process so I could just pass
it and item and it would take care of saving it properly? Is it worth
bothering with?

I’ve got a very similar situation where I’ve been just copy/pasting, as
you have been, but seeing your question laid out so cleanly makes me
think of a possible solution. This ought to be handle-able by passing
in the actual class of which a new instance is needed. Everything in
Ruby is an object, right? So I am going to try something like this:

def add_item( type, symbol )
@item = type.new(params[symbol])
if @item.save
// do the things
end
end

and call it like this:

add_item( Entry.class, :entry )

and see what happens. I don’t know if things work this way in Ruby and
I don’t have time to play with this project again until tomorrow, alas,
so I might be completely wrong here.

Rachel