ruby-on-rails - 我如何在 Rails 4 中为需要两个以上投票选项的博文创建投票系统?

标签 ruby-on-rails ruby rubygems vote

我建立了一个非常简单的 Rails 博客,该博客基于现实生活中类似治疗的类(class)。在每篇博文的末尾,用户可以对写着“这让你感觉如何?”的帖子投票。

我快要完成应用程序的开发了,但我不知道如何制作一个扩展的投票系统。

用户需要能够对 6 种不同的情绪选项进行投票(快乐、悲伤、愤怒、鼓舞、无聊、焦虑)。这意味着一票并不比另一票好。没有赞成票和反对票。它们只是不同。

到目前为止,我遇到的所有 gems 和教程都具有一个由两个选项组成的投票系统。我需要一种方法来实现 6。

最后,我希望能够计算属于特定博客文章的所有情绪,并在标题旁边显示得票最多的情绪。

有没有人试过这样的事情?在我弄清楚如何做到这一点之后,如果还没有的话,我想把它做成一颗 gem 。

最佳答案

(我假设用户只为每个帖子投一票,并且您使用的是最新的 Rails 4.2)

只需创建一个引用UserPost 的新表,它有一个我们将要使用的整数字段the new enum与,例如。 Vote 使用整数字段 choice,因此模型将是:

class Vote < ActiveRecord::Base
  belongs_to :user
  belongs_to :post

  enum choice: %i[happy sad angry inspired boring anxious]
end

并且您的UserPost 模型都将has_many :votes

然后(根据文档)您使用 Vote.choices 将名称的哈希值转换为整数(您将使用它来填充您的 View )。

...最后,您将获得博客文章的情绪计数散列:

post.votes.group('votes.choice').count

我相信您可以在那里获得最多的选票。

更新

OP 在评论中问我是在哪里发现的,我认为我对他的回应可能会对其他人有所帮助:

Hmm, well aside from the docs that I already linked you to in my answer, I follow the rails-core mailing list which announces and discusses upcoming features, I follow @rails on twitter where they announce all sorts of things, I read the release notes for new versions and I go through the release notes in the guides after major releases.

关于ruby-on-rails - 我如何在 Rails 4 中为需要两个以上投票选项的博文创建投票系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114846/

相关文章:

ruby-on-rails - CSV 解析返回 "Unquoted fields do not allow\r or\n"但在源文件中找不到错误?

ruby-on-rails - 如何在 Rails 3 中使用 gem 而不在 Gemfile 中引用它

ruby-on-rails - 将 Rails 3.2 升级到 4.2 -> 无法加载此类文件 -- resque_scheduler/tasks

javascript - 在我的应用程序中为 HTML/CSS 编辑哪些文件 (ruby)

ruby-on-rails - 获取自定义 attr_accessor 的未定义方法 `validates_presence_of'

ruby-on-rails - 在 let() 中使用哈希

ruby-on-rails - Passenger 是否/可以使用像 Mongrel 这样的集群?

ruby - RSpec - 如何测试是否调用了不同类的方法?

ruby-on-rails - rake : List/Remove custom rake task in specific environment (development/production )

mysql - 在 Ruby on Rails 中列出数据库中的可用表