使用[Rails 4]投票系统的问题

时间:2014-01-31 21:24:11

标签: ruby-on-rails ruby-on-rails-4

我正在创建一个系统,人们可以投票或回答数据库中保存的一些问题。基本上问题可以有两个或几个答案(答案可以通过复选框或单选按钮选择,具体取决于问题的类型)

我的模型如下:

问题模型

class Question < ActiveRecord::Base
  has_many :answers, dependent: :destroy
  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:answer].blank? } 
end

答案模型

class Answer < ActiveRecord::Base
  belongs_to :question
  has_many :votes
end

用户模型

class User < ActiveRecord::Base 
  has_many :votes
end

投票模型

class Vote < ActiveRecord::Base
  belongs_to :user
  belongs_to :answer
end

这或多或少是我想要做的形式,它首先显示问题然后选择选项,复选框或单选按钮的答案,然后是提交按钮以保存投票 http://i.stack.imgur.com/x3zdr.png或见下文 enter image description here

如何构建表单的任何建议都会非常感谢!!!

路线:

$ rake routes
            votes GET    /votes(.:format)                                   votes#index
                  POST   /votes(.:format)                                   votes#create
         new_vote GET    /votes/new(.:format)                               votes#new
        edit_vote GET    /votes/:id/edit(.:format)                          votes#edit
             vote GET    /votes/:id(.:format)                               votes#show
                  PATCH  /votes/:id(.:format)                               votes#update
                  PUT    /votes/:id(.:format)                               votes#update
                  DELETE /votes/:id(.:format)                               votes#destroy

1 个答案:

答案 0 :(得分:1)

我会这样做:

#config/routes.rb
resources :questions do 
    resources :votes, only: [:new, :create], as: "vote", path: "vote" #-> /questions/1/vote
end

#app/controllers/votes.rb
def new
    @question = Question.find(params[:question_id])
    @vote = Vote.new
end

def create
    @vote = Vote.new(vote_params)
    @vote.save
end

private

def vote_params
    params.require(:vote).permit(:answer_id).merge(user_id: current_user.id)
end

#app/views/votes/new.html.erb
<%= form_for @vote do |f| %>
    <%= @question.title %>

    Answers:
    <% @question.answer.each do |answer| %>
        <%= f.radio_button :answer_id, answer.id %> #-> need to check syntax
    <% end %>
    <%= f.submit "Go" %>

<% end %>

这将使用相应的answer_iduser_id提交投票。虽然我觉得它也应该question_id