Question 1
I am dealing with a database that holds products and it has a datetime
field called “active_at”. so I have the following for active_at:
<%= f.datetime_select :active_at %>
It gives me 5 different params:
params[:product][:active_at(1i)]
params[:product][:active_at(2i)]
params[:product][:active_at(3i)]
params[:product][:active_at(4i)]
params[:product][:active_at(5i)]
How do I convert this into a Time object?
Question 2
What if I have another field called “is_active” and its just a boolean.
If it’s set to false then active_at gets set to nil. Is there any easier
way than just:
if params[:client][:is_active] == “1”
(1…5).each {|num| params[:product].delete(“active_at(#{num}i)”)}
params[:product][:active_at] = nil
end
Isn’t there a cleaner way to do this?
Thanks for your help.
Ben J. wrote:
Question 1
I am dealing with a database that holds products and it has a datetime
field called “active_at”. so I have the following for active_at:
<%= f.datetime_select :active_at %>
It gives me 5 different params:
params[:product][:active_at(1i)]
params[:product][:active_at(2i)]
params[:product][:active_at(3i)]
params[:product][:active_at(4i)]
params[:product][:active_at(5i)]
How do I convert this into a Time object?
Hi Ben
Internally Rails/Activerecord does lot of smart datatype
conversion/transformations
if you see 1i…5i it has a naming convention, it automatically gets
converted to time object
@active_at = params[:product][:active_at]
same way when you query from db the timestamp is converted to a Time
object
Question 2
What if I have another field called “is_active” and its just a boolean.
If it’s set to false then active_at gets set to nil. Is there any easier
way than just:
if params[:client][:is_active] == “1”
(1…5).each {|num| params[:product].delete(“active_at(#{num}i)”)}
params[:product][:active_at] = nil
end
you can implement that logic in model instead of controller
you can hook your logic into rails callbacks
http://rubyonrails.org/api/classes/ActiveRecord/Callbacks.html
def before_save
active_at = nil if is_active.nil? || is_active <= 0
end
regards
A.Senthil N.
http://senthilnayagam.com