4

有什么问题?:

我正在创建一个通用博客,并致力于创建基本功能。问题是视图(有多少人看过特定帖子)没有正确显示。

最新技术: .

此时我有两个控制器/模型:发布和评论。我将为您提供我的架构,以帮助您更好地了解情况。

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

我所做的: 在帖子控制器中,每当有人创建帖子时,我尝试通过将其设置为 0 来初始化视图。

# 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

并且帖子应该能够显示其观看次数。所以在 post 的 show.html.erb 文件中,我也添加了下面的部分。 <p> <b>views:</b> <%= @post.view %> </p>

它是如何工作 的:根本没有显示视图数量。我检查了数据库,即使每当用户添加帖子时我尝试将其初始化为 0,该列也是空白的。我猜我尝试访问“视图”变量的方式有问题?通过@view = @post.view访问它是不是不对 ?

我知道我必须考虑一个已经看过帖子的用户是否重新访问,但在我确切知道如何访问视图变量/初始化/增加它之前,我还没有到那里。

非常感谢您提前提供的帮助!

-最大限度

4

1 回答 1

2

在调用 @post.save之前将 Post 的 view 属性初始化为零(作为 if 语句的副作用):

@post.view = 0

然后在呈现帖子的控制器操作中,您需要将帖子的视图属性更新 1。如果多个人在数据库读取和写入之间同时访问该页面,这将出现问题,但它至少会让您进入正确的方向。

保存数据库后将@view此处的值分配给什么也没做。

于 2012-11-11T01:40:24.993 回答