Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 142 Lecture Notes: FormsSlide 1 Simple Form Product: Price:

Similar presentations


Presentation on theme: "CS 142 Lecture Notes: FormsSlide 1 Simple Form Product: Price:"— Presentation transcript:

1 CS 142 Lecture Notes: FormsSlide 1 Simple Form Product: Price:

2 Slide 2 Rails Form Helpers <input id="student_name" name="student[name]“ size="30" type="text" value="Chen" /> <input id="student_birth" name="student[birth]“ size="30" type="text" value="1990-02-04" /> <input name="commit" type="submit“ value="Modify Student" /> Describes type, provides initial values Object representing form

3 CS 142 Lecture Notes: FormsSlide 3 Customize Format...

4 CS 142 Lecture Notes: FormsSlide 4 Post Action Method def update @student = Student.find(params[:id]) ]) @student.name = params[:student][:name] @student.birth = params[:student][:birth] @student.gpa = params[:student][:gpa] @student.grad = params[:student][:grad] if @student.save then redirect_to(:action => :show) else render(:action => :edit) end Hash with all of form data Redirects on success Redisplay form on error

5 Security checks in Rails 4 cause update to fail CS 142 Lecture Notes: FormsSlide 5 More Compact Approach def update @student = Student.find(params[:id]) if @student.update(params[:student]) then redirect_to(:action => :show) else render(:action => :edit) end

6 CS 142 Lecture Notes: FormsSlide 6 Rails 4 Pattern def update @student = Student.find(params[:id]) if @student.update(student_params( params[:student])) then redirect_to(:action => :show) else render(:action => :edit) end private def student_params(params) return params.permit(:name, :birth, :gpa, :grad) end Creates new hash containing only specified elements

7 CS 142 Lecture Notes: FormsSlide 7 Creating New Record def create @student = Student.new(student_params( params[:student]) if @student.save() then redirect_to(:action => :show) else render(:action => :edit) end

8 CS 142 Lecture Notes: FormsSlide 8 Validation (in Model) class Student < ActiveRecord::Base validates_format_of :birth, :with => /\d\d\d\d-\d\d-\d\d/, :message => "must have format YYYY-MM-DD" def validate_gpa if (gpa 4.0) then errors.add(:gpa, "must be between 0.0 and 4.0") end validate :validate_gpa end Custom validation method Built-in validator Saves error info

9 CS 142 Lecture Notes: FormsSlide 9 Error Messages :update, id: @student.id}) do |form| %>......

10 CS 142 Lecture Notes: FormsSlide 10 File Uploads with Rails...... In form post method: params[:student][:photo].read() params[:student][:photo].original_filename

11 CS 142 Lecture Notes: CookiesSlide 11


Download ppt "CS 142 Lecture Notes: FormsSlide 1 Simple Form Product: Price:"

Similar presentations


Ads by Google