ruby-on-rails - Rails,参数丢失或值:投票为空
问题描述
我有一个投票模型,它有一个candidate_vote:integer,它也有一个候选人之间的关联。我尝试创建一个表单,但我得到这个错误参数丢失或值为空:投票
这是表格
<%= form_for @vote do |f| %>
<table>
<tbody>
<% Position.includes(:candidates).order(:name).each do |position| %>
<tr>
<th colspan="5"><%= position.name %></th>
</tr>
<% position.candidates.each do |candidate| %>
<tr>
<td><%= image_tag(candidate.image, :size => '50x50') if candidate.image.attached? %></td>
<td><%= candidate.name %></td>
<td><%= candidate.info %></td>
<td><%= check_box_tag :candidate_votes, checked_value: '1', unchecked_value: '0' %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
<%= f.submit "Submit" %>
<% end %>
和控制器
class VotesController < ApplicationController
def new
@vote = Vote.new
@candidates = Candidate.all
end
def create
@vote = Vote.create(vote_params)
if @vote.save
redirect_to @vote
else
render :new
end
end
private
def vote_params
params.require(:vote).permit(:candidate_vote, :candidate_id)
end
end
及其各自的型号
class Vote < ApplicationRecord
belongs_to :candidate
end
class Candidate < ApplicationRecord
belongs_to :position
belongs_to :user
has_many :votes
has_one_attached :image
validates :image, presence: true, content_type: ['image/jpg', 'image/jpeg', 'image/png']
validates :name, presence: true
validates :info, presence: true
end
请问有什么问题或者我做错了什么?
解决方案
I hate ERB, have some nice HAML:
= form_for @vote do |f|
%table
%tbody
- Position.includes(:candidates).order(:name).each do |position|
%tr
%th{colspan: 5}= position.name
- position.candidates.each do |candidate|
%tr
%td= image_tag(candidate.image, :size => '50x50') if candidate.image.attached?
%td= candidate.name
%td= candidate.info
%td= check_box_tag "vote[candidate_votes[#{candidate.id}]]", checked_value: '1', unchecked_value: '0'
= f.submit "Submit"
as zhisme says, you aren't passing the id of the candidate through the form.
I'm assuming that you want the person to be able to vote for more than one candidate? if you don't, it might be worthwhile looking at the "radio_button" object, and returning the candidate as the value. e.g.:
= form_for @vote do |f|
%table
%tbody
- Position.includes(:candidates).order(:name).each do |position|
%tr
%th{colspan: 5}= position.name
- position.candidates.each do |candidate|
%tr
%td= image_tag(candidate.image, :size => '50x50') if candidate.image.attached?
%td= candidate.name
%td= candidate.info
%td= f.radio_button :candidate_votes, candidate.id
= f.submit "Submit"
推荐阅读
- google-distancematrix-api - 谷歌地图距离矩阵交通假设
- docker - 无法连接到 GitLab 的 Docker 守护进程
- android - 在 recyclerview 标头中实现 SearchView
- javascript - 反应等待语法
- javascript - 如何使用 useSound 使用多种声音 - React Js
- ios - WKWebView 无效
- r - 在 rmarkdown 中创建弹性表后,我可以过滤掉弹性表中的行吗?
- elasticsearch - 在现有索引中创建一个新字段 - ElasticSearch
- flutter - Flutter BLoC 测试失败
- c# - LINQ GroupBy 和项目使用其键列表和 ToDictionary 的结果键入