首页 > 解决方案 > 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

请问有什么问题或者我做错了什么?

标签: ruby-on-railsruby

解决方案


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"

推荐阅读