What’s the problem?:
I am creating a general blog, and working to create the essential features.
The problem is that the view (how many people have seen a particular post) is not shown correctly.
The state of art:.
I have two controllers/models at this point: Post and Comment. I will provide you with my schema to help you understand the situation better.
create_table "comments", :force => true do |t|
t.string "name"
t.text "body"
t.integer "like"
t.integer "hate"
t.integer "post_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "comments", ["post_id"], :name => "index_comments_on_post_id"
create_table "posts", :force => true do |t|
t.string "name"
t.text "content"
t.integer "view"
t.integer "like"
t.integer "hate"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
What I have done:
In the Post Controller, I tried to initialize the views by setting it to 0 whenever someone creates a post.
# POST /posts
# POST /posts.json
def create
@post = Post.new(params[:post])
@view = @post.view
@view = 0
respond_to do |format|
if @post.save
format.html { redirect_to posts_path, notice: 'success.' }
format.json { render json: @post, status: :created, location: @post }
@view = @post.view
@view = 0
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
And the post should be able to show its number of views. So in the show.html.erb file of post, I added the part below as well.
<p>
<b>views:</b>
<%= @post.view %>
</p>
How it doesn’t work:
The number of views is simply not shown at all. I checked the database, and the column was blank even if I attempted to initialize it to 0 whenever a user adds a post. I’m guessing there is a problem with the way I try to access the “view” variable? Is it not right to access it by doing
@view = @post.view?
I’m aware of the fact that I’ll have to consider if a user that’s already seen the post revisits, but I’m not there yet until I know exactly how to access the view variable/initialize/increment it.
I really appreciate your help in advance!
-Max
To initialize Post’s view attribute to zero, before invoking @post.save (as a side effect of the if statement):
Then in your controller actions that render the post you will need to update a Post’s view attribute by 1. This will have problems if multiple people access the page at the same time between database reads and writes but it will at least get you moving in the right direction.
Assignments of
@viewhere to values after saving the database are accomplishing nothing.