Go Back   CodingForums.com > :: Server side development > Ruby & Ruby On Rails

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-15-2007, 07:43 PM   PM User | #1
ralph l mayo
Regular Coder

 
ralph l mayo's Avatar
 
Join Date: Nov 2005
Posts: 951
Thanks: 1
Thanked 31 Times in 29 Posts
ralph l mayo is on a distinguished road
Can you expand an array of N to fill N functional arguments?

I've made this abstract class other classes can implement to make themselves storable in a MPTT database scheme without having knowledge of the left/right juggling. In the new entry part of class, I need to be able to insert an arbitrary length hash (@attrs) into the database (using DBI). I can generate the SQL for N values, but when it comes to executing it the SQL DBI's execute() method will not expand an array to fill the arguments it is expecting.

I tried this first:
Code:
	cursor = @dbd.prepare(
		"INSERT INTO #{ @table } (#{ @columns['left'] }, #{ @columns['right'] }, #{ @attrs.keys.join(', ') }) 
			VALUES (?, ?#{ ', ?' * @attrs.length })")
	
		cursor.execute(l, l + 1, @attrs.values)
But execute() fails for @attrs.length > 1

This works, but it's very hackish:
Code:
	exec_attrs = @attrs.keys.collect { |k| "@attrs['#{ k }']" }
	eval "cursor.execute(l, l + 1, #{ exec_attrs.join(', ') })"
So, any better way to do it? Aside from rewriting execute() to handle arrays the way I want, which I may end up doing.
ralph l mayo is offline   Reply With Quote
Old 04-01-2007, 07:04 AM   PM User | #2
ralph l mayo
Regular Coder

 
ralph l mayo's Avatar
 
Join Date: Nov 2005
Posts: 951
Thanks: 1
Thanked 31 Times in 29 Posts
ralph l mayo is on a distinguished road
I still don't have a general solution for this but there's a mechanism in DBI that fixes this instance:

Instead of
Code:
cursor.execute(l, l + 1, @attrs.values)
You can do
Code:
cursor.bind_param(1, l)
cursor.bind_param(2, l + 1)
@attrs.each_with_index { |at, idx|
    cursor.bind_param(idx + 3, at[1])
}
Much better.
ralph l mayo is offline   Reply With Quote
Old 11-06-2007, 04:22 PM   PM User | #3
JessicaW
New to the CF scene

 
Join Date: Nov 2007
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
JessicaW is an unknown quantity at this point
ralph l mayo, thanks for reply
code you pasted work fine
JessicaW is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:47 AM.


Advertisement
Log in to turn off these ads.