[英]Questions Voting System with [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或参见下文
关于如何构建表格的任何建议都将非常感激!
路线:
$ 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
我会这样:
#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_id
和user_id
提交投票。 虽然我觉得它也应该有question_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.