Reputation: 11460
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
Upvotes: 0
Views: 468
Reputation: 49344
hash.each do |k,v|
date = k.split('_')[1]
Entry.create(:date => date, :price => v)
end
Upvotes: 6