Reputation: 1447
I have a basic blog setup on one of my apps. Each blog
has a boolean for whether it is published
and then a date for when it is published_on
. The published_on
is nil
until it updates with published
as true
. The controller logic is like this:
def create
@blog = Blog.new(blog_params)
@blog.user_id = current_user.id
if @blog.published
@blog.published_on = Time.now
end
respond_to do |format|
if @blog.save
format.html { redirect_to @blog, notice: 'Blog was successfully created.' }
format.json { render :show, status: :created, location: @blog }
else
format.html { render :new }
format.json { render json: @blog.errors, status: :unprocessable_entity }
end
end
end
And for update...
def update
if @blog.published && @blog.published_on.nil?
@blog.published_on = Time.now
end
...
end
However, the update function doesn't update and I get a undefined method 'strftime' for nil:NilClass
error for where it should display on the show
page. When I rails c
it, the published_on
didn't save.
What should I be putting instead of the Time.now
logic I currently have in the controller. It works fine with the blog#create
, but something is going wrong in the blog#update
.
Upvotes: 0
Views: 355
Reputation: 2727
I think the controller might be the wrong place. You could implement a after_save callback in your model. There you can set the timestamp self.published_on = DateTime.now if self.published
after_save :set_published_at
def set_published_at
self.published_on = DateTime.now if self.published
end
Upvotes: 1
Reputation: 46489
Have you tried DateTime.now instead of Time.now? They are different classes and I'm not sure a datetime attribute can be directly assigned to a Time object.
@blog.published_on = DateTime.now
Upvotes: 0