Rails: how to implement the number of message views?

What is the problem ?:

I am creating a common blog and working on creating the necessary features. The problem is that the view (how many people saw a particular post) is not shown correctly.

Condition:.

I have two controllers / models at the moment: Post and Comment. I will give you my outline to help you better understand the situation.

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 did: In Post Controller, I tried to initialize the views by setting it to 0 when someone creates a message.

 # 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 message should be able to show its number of views. Therefore, in the show.html.erb file of the message, I also added the part below. <p> <b>views:</b> <%= @post.view %> </p>

How it does not work: The number of views is simply not displayed at all. I checked the database and the column was empty even if I tried to initialize it to 0 when the user adds a message. I assume there is a problem with how I am trying to access the variable "view"? Is it wrong to address him by doing
@view = @ post.view?

I know that I will need to think about whether a user who has already seen that the message is being reviewed, but so far I do not know how to access the variable of the form / initialize / increase it.

I really appreciate your help in advance!

-Max

+4
source share
1 answer

To initialize the Post view attribute to zero, before calling @ post.save (as a side effect of the if statement):

 @post.view = 0 

Then in your controller actions that display the message, you will need to update the Post view attribute to 1. This will have problems if several users simultaneously access the page between reads and the database record, but at least you get moving in the right direction.

The @view here for values ​​after saving the database do nothing.

+2
source

Source: https://habr.com/ru/post/1445280/


All Articles