任何人都可以帮我将这些表单值保存在数据库中。我已经创建了一个表单。当我点击提交按钮时,会出现以下验证消息。
1 error prohibited this post from being saved:
Gender must be accepted
请检查代码并帮我保存DB中的所有值。如果发现任何错误,请将其更正。
我的代码如下:
视图/生/ index.html.erb
<h1>Choose the option</h1>
<p>
<%= link_to "Enter student data",students_new_path %>
</p>
<p>
<%= link_to "Display your data",students_show_path %>
</p>
views/students/new.html.erb
<h1>Enter your data</h1>
<%= form_for @student,:url => {:action => 'create'} do |f| %>
<% if @student.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@student.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @student.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="name">Name:</label>
<%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
<label for="gender">Gender:</label><br>
<%= f.radio_button :gender,'Male',:checked => true %>
<%= f.label :Male %>
<%= f.radio_button :gender,'Female' %>
<%= f.label :Female %>
</p>
<p>
<label for="city">Select the City</label>
<%= f.select(:city,options_for_select([['Bhubaneswar','Bhubaneswar'],['Cuttack','Cuttack'],['Behrempur','Behrempur'],['Puri','Puri']],selected: "Puri")) %>
</p>
<p>
<%= f.check_box :terms_service %> accept terms and service
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
控制器/ students_controller.rb
class StudentsController < ApplicationController
def index
end
def show
end
def new
@student=Student.new
end
def create
@student=Student.new(users_params)
if @student.save
flash[:notice]="You have signed up successfully.."
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:notice]="You have not signed up successfully"
flash[:color]="invalid"
render :new
end
end
private
def users_params
params.require(:student).permit(:name,:gender,:city,:terms_service)
end
end
模型/ student.rb
class Student < ActiveRecord::Base
validates :name ,:presence => true,:length => { :minimum => 6 }
validates :gender, :acceptance => true
validates :terms_service, :acceptance => true
end
迁移\ 20150114061737_create_students.rb
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
t.string :name
t.string :gender
t.string :city
t.string :terms_service
t.timestamps null: false
end
end
end
请帮我成功运行此代码。谢谢提前..
答案 0 :(得分:0)
用于性别字段的验证类型错误,即当您要检查用户是否在表单中选中复选框时,会使用验收验证。在您的情况下,您应该使用
validates :gender, :presence => true