Rails:评级向上或向下计数器,丢失

发布于 2025-01-07 17:38:26 字数 769 浏览 0 评论 0原文

我目前正在尝试创建一个具有向上或向下功能的评级计数器。我很困惑是否应该在我的帖子中添加一列来显示一个人喜欢该帖子,或者创建一个单独的模型来显示评级计数器,但该计数器属于该帖子。类似于 Reddit 甚至 Stackoverflow 的东西。另外,我将如何开始这个评级计数器,以哪种方法是正确的方法?谢谢大家。

编辑 - 目前不知道如何从这里继续

评级

class Rating < ActiveRecord::Base
  attr_accessible :post_id, :user_id, :rating
  has_many :post
  has_many :users

  validates :post_id, presence: true

end

评级控制器

class RatingController < ApplicationController

  def create
    @post = Post.find(params[:id])
    @post.rating_count = @post.rating_count + 1
  end
end

评级表格

<%=form_tag @rating do %>
<%=submit_tag :Rating%>
<%end%>

I am currently trying to create a rating counter that has a up or down feature to it. I am confused to if I should add a column to my post to show that a person likes the post or create a separate model to show the rating counter but the counter belongs to the post. Something along the lines of Reddit or even Stackoverflow's. Also, how would I start on this rating counter, to whichever method is the right method? Thank you everyone.

Edit - Currently stuck on how to move on from here

Rating

class Rating < ActiveRecord::Base
  attr_accessible :post_id, :user_id, :rating
  has_many :post
  has_many :users

  validates :post_id, presence: true

end

Rating Controller

class RatingController < ApplicationController

  def create
    @post = Post.find(params[:id])
    @post.rating_count = @post.rating_count + 1
  end
end

Rating Form

<%=form_tag @rating do %>
<%=submit_tag :Rating%>
<%end%>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枕头说它不想醒 2025-01-14 17:38:26

您应该创建一个单独的模型,它将存储 user_id、post_id 和评级列。

class Post < ActiveRecord::Base
  has_many :ratings
end

class Rating < ActiveRecord::Base
  has_many :posts
  has_many :users
end

然后,您将能够获取相应帖子的所有评级、相应用户的帖子评级等等。

您甚至可以创建多态关系来为其他模型提供评级功能:

class Post < ActiveRecord::Base
  has_many :ratings, as: :rateable
end

class Rating < ActiveRecord::Base
  has_many :rateable, polymorphic: true
  has_many :users
end

You should create a separate model, which will store user_id, post_id and a rating columns.

class Post < ActiveRecord::Base
  has_many :ratings
end

class Rating < ActiveRecord::Base
  has_many :posts
  has_many :users
end

Then you`ll be able to fetch all rating for the appropriate Post, the Post`s rating for the appropriate user and so on.

You can even create a polymorphic relation to provide ratings functionality for other models:

class Post < ActiveRecord::Base
  has_many :ratings, as: :rateable
end

class Rating < ActiveRecord::Base
  has_many :rateable, polymorphic: true
  has_many :users
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文