Reputation: 8988
Im learning rails and exploring a bit away from the book and creating a simple application with added functionality as i increase my knowledge. Im writing a simple blog application and i have a field in the form called date added, i don't want this to be a field i want it to get the date from the server and place it in to the database automatically. How would i go about doing this? I was thinking of a hidden field but then unsure on how to process the date and insert it to the hidden field. Is this the wrong way of going about things?
Thanks in Advance,
Dean
Upvotes: 2
Views: 6252
Reputation: 3671
here is the view (new) of a form displaying the current date :
<% form_for(@recipe) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p><b>date</b><br/>
<%= f.datetime_select :date %>
</p>
<p>
<%= f.label :instructions %><br />
<%= f.text_area :instructions %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', recipes_path %>
and the controller :
def new
@recipe = Recipe.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @recipe }
end
end
Upvotes: 1
Reputation: 115372
In Rails if you give your models attributes with certain names then ActiveRecord gives them special behaviour. There are four different date/time related ones:
created_on
: gets automatically set to the date the record was createdcreated_at
: gets automatically set to the date and time the record was createdupdated_on
: gets automatically set to the date the record was updatedupdated_at
: gets automatically set to the date and time the record was updatedTypically the created_at
/updated_at
pair get added to a model automatically by the t.timestamps
declaration in the model's associated ActiveRecord Migration.
Upvotes: 0
Reputation: 18175
I would not use a hidden field, because even if it is hidden the user can manipulate this. I think the best way to solve this problem is, ignore the date in the form and add the date to you your model in the controller action right before saving the object:
def SomeController
#...
def create
@model = Model.new params[:model]
@model.date_field_name = Time.now
if @model.save
# whatever should be done if validation passes or
redirect_to @model
else
# whatever should be done if validation fails or
render :new
end
end
#...
end
But you don't have to do any of this, because ruby on rails offers the two columns created_at
and updated_at
. created_at
will be set when the object gets created and updated_at
will be set every time when you update this object.
Upvotes: 7