I have a form that allows a user to create a post with a title, body,
image and a tag. All fields are required using validates_presence_of and
has_attached_file in the model.
Since every post has a tag, there is a page for each tag that has all
the posts with that tag paginated on it. When this tag (show) view
reaches a specified limit, I want the oldest post with that tag deleted
as a new one is created.
This is what I think I have to do: before a post is saved, I have to
find how many posts exist with that tag, if more than (let’s say) 20
exist, delete the post with the oldest “updated_at” value that belongs
to that tag.
In my tags (show) view I use this code to show how many posts for a tag
exist:
[code=]<% post.tag_counts.each do |tag| %>
Posts for this topic: <%= tag.count %>
<% end %>[/code] When I create a post, this is what is used in my posts_controller currently: [code=] def create @post = Post.new(params[:post]) respond_to do |format| if @post.save #@old_post = Post.first #@old_post.destroy flash[:notice] = "Post successfully created." format.html { redirect_to(:controller => "tags") } else flash.now[:error] = "Error creating post." format.html { render :action => "new" } end end end[/code] I use this form to create a post: [code=]<% form_for @post, :html => { :multipart => true } do |f| %> <%= f.label :title %><%= f.text_field :title %>
<%= f.label ‘Image’ %>
<%= f.file_field :image %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.label ‘Topic’ %>
<%= f.text_field :tag_list %>
<%= f.submit ‘Create’ %>
<% end %>[/code]
Before each post is created, I need to somehow check how many posts have
the tag that the user has entered in the form (<%= f.text_field
:tag_list %>). So if that tag doesn’t exist, it should create the post.
If that tag already exists, it should check how many posts for that tag
exist and if the amount of posts that belong to it is less than 20,
create the post, if the amount of posts that belong to that tag equal or
is greater than 20, it should delete the post with the oldest
‘updated_at’ value (and create the post).
I’m not completely sure but I think I have to add this to the create
method in my posts controller. Can someone push me in the right
direction?