2015-01-14 52 views
0

任何人都可以幫助我將這些表單值保存在數據庫中。我已經創建了一個表單。當我單擊提交按鈕時,下面的驗證信息即將到來。如何使用ROR在數據庫中保存表單值

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 

migrat Ë\ 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 

請幫我提前運行這段代碼successfully.Thanks ..

回答

0
時要檢查是否用於性別字段

驗證類型是錯誤的,即接受驗證用於複選框由用戶在表單中檢查。在你的情況下,你應該使用

validates :gender, :presence => true 
相關問題