Exploring & Validating Models
Master Rails Console and Model Validation Techniques
Core Ruby on Rails Tools
Rails Console
Interactive command-line interface similar to IRB that provides direct access to Rails functions and database manipulation capabilities.
Model Validation
Built-in Rails helper methods that ensure data integrity by validating record fields before database operations.
Database Operations
Complete CRUD functionality through console commands for creating, reading, updating, and deleting records.
Environment Setup Process
Navigate to Project Directory
Use Terminal to change into your Rails project folder using cd command and drag-drop functionality
Launch Rails Server
Execute 'rails server' command to start the development server on localhost:3000
Open Rails Console
Open new Terminal tab and run 'rails console' to access the interactive Rails environment
Rails automatically uses placeholder techniques with question marks to protect against SQL injection attacks. This security feature is built into Rails query methods and helps prevent malicious SQL execution.
Console vs Controller Syntax
| Feature | Rails Console | Controller File |
|---|---|---|
| Finding Records | Movie.find(1) | Movie.find(params[:id]) |
| Variable Assignment | movie = Movie.find(1) | @movie = Movie.find(params[:id]) |
| Instance Variables | Not required | Required with @ symbol |
Creating New Movie Record
Initialize New Object
Use Movie.new to create empty movie object with all nil values
Assign Field Values
Set title, description, placement, rating, and other string/integer/boolean fields
Save to Database
Execute movie.save to persist the record and generate SQL insert statements
Remember that runtime is an integer (no quotes), has_subtitles is boolean (no quotes), while strings like title and description require quotation marks. Rails is flexible about data entry methods.
Changes made to object attributes in Rails console are not automatically saved to the database. You must explicitly call the save method to persist modifications.
Console Operation Methods
Create Method
Movie.create combines new and save operations into single action, immediately persisting the record to database.
Destroy Method
Can be chained directly onto find_by commands to locate and delete records in one operation.
Method Chaining
Rails allows chaining operations like Movie.find_by(title: name).destroy for efficient command execution.
Model Validation Implementation
Ensures title, mpaa_rating, runtime, and poster_image fields exist before saving
Validates that runtime field contains only numeric values
Restricts MPAA rating to specific allowed values in predefined array
Add error handling logic to form template for user feedback
Rails stores validation errors in @movie.errors but doesn't automatically display them. Custom template logic using full_messages.collect and html_safe methods is required to show errors to users.
Key Takeaways
