views:

78

answers:

1

I have a list of params with names and values like this:

date_2009-09-16 => ["50.00"]
date_2009-09-17 => ["60.00"]
date_2009-09-18 => ["90.00"]

I would like to save a record in my database for each date like this:

|id | date       | price|
|1  | 2009-09-16 | 50.00|
|2  | 2009-09-17 | 60.00|
|3  | 2009-09-18 | 90.00|

How do I extract the date from the param name (is this possible?!) ?

Update:

Whilst I'm still not sure about how to do Eimantas' answer, can I clarify the params my form is sending:

Parameters: {
"commit"=>"Save",
"method"=>"put",
"controller"=>"rates",
"action"=>"create",
"authenticity_token"=>"A0wP8Dq7cVOM+bLIcdPENzRhg6T1Mwhjqob1UYTk1Jk=",
"date_2009-09-16"=>"50.00",
"date_2009-09-17"=>"60.00",
"date_2009-09-18"=>"90.00",
"rate"=>{"year"=>"2009", "product_type_id"=>"2"}
}

I think the dates should belong inside the rate part of the params hash, but Rails isn't putting them in there.

Update 2:

I'm wondering if you can see my Rate table, then it might help nail this for me (and prevent your frustration!). I'm trying to allow a customer to put 30 values in 30 boxes in my view (one for each day of September in this example), and in my controller, after they've hit Save, have it save the 30 records.

id | date       | price | product_type_id |
.. | ..         | ..    | ..              |
16 | 2009-09-16 | 50.00 | 1               |
17 | 2009-09-17 | 60.00 | 1               |
18 | 2009-09-18 | 90.00 | 1               |
.. | ..         | ..    | ..              |

I thought about using one hidden field to hold the date, and one visible field to hold the price, but how will Rails know which date goes with which price in the create action? Sorry if this is so confusing.

Thanks in advance!

Gav

+6  A: 
hash.each do |k,v|
  date = k.split('_')[1]
  Entry.create(:date => date, :price => v)
end
Eimantas
Excuse me if I'm being dumb, but how do I create 'hash'?
Gav
hash just contains your the keys in your params that match date_. for example: hash = params.select { |k,v| k ~= /^date_.*/ }. Now, why do you have these weird named params is another question ;)
hgimenez
Thanks hgimenez. The reason for the weirdly named params is that I'm trying to create and update multiple records at once. I've watched Ryan Bates' Railscasts - Episode 52 (Update through Checkboxes) and trying to achieve similar functionality, but with a text field instead of the checkbox. The problem I'm trying to solve, is each field should have a price in it, for a particular date; but text fields like all form fields only allow name=value pairs! (Does that help you understand my insanity?! :-) )
Gav
Accepted this as the answer, because it does answer my original question. Thanks Eimantas! :-)
Gav
Glad to help! Sorry i wasn't around and couldn't answer your hash-related question ,)
Eimantas