UD, Validations, Associations, Params
AND
Create, read, update, destroy
/users/5/edit (GET)
@user = User.find(params[:id)
/users/5 (PUT)
user = User.find(params[:id)
user.update_attributes(user_params)
/users/5 (DELETE)
user = User.find(params[:id])
user.destroy
class UsersController < ApplicationController
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
redirect_to user_path(@user)
else
render 'edit'
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to root_path
end
private
def user_params
params.require(:user).permit(:name)
end
end
YOU ARE HERE
validates :attribute, { validators }
OR
validates_validator_of [ :attributes ]
has_many
belongs_to
class Student < ActiveRecord::Base
has_many :grades
end
class Grade < ActiveRecord::Base
belongs_to :student
end
name | age | major | id |
---|---|---|---|
Bob | 20 | EECS | 1 |
Alice | 19 | Bio | 2 |
id | grade | student_id |
---|---|---|
100 | 4 | 1 |
101 | 3 | 1 |
Primary Key
Foreign Key
name | age | major | id |
---|---|---|---|
Bob | 20 | EECS | 1 |
Alice | 19 | Bio | 2 |
id | grade | student_id |
---|---|---|
100 | 4 | 1 |
101 | 3 | 1 |
Primary Key
Foreign Key
student = Student.find(1)
student.grades
def show
@user = User.find params[:id]
end
class PostsController < ApplicationController
def index
@post = Post.new
@posts = Post.all
end
def create
puts params
@post = Post.new post_params
@post.save
redirect_to root_path
end
def like
end
private
def post_params
params.require(:post).permit(:text)
end
endclass PostsController < ApplicationController
def index
@post = Post.new
@posts = Post.all
end
def create
puts params
@post = Post.new post_params
@post.save
redirect_to root_path
end
def like
end
private
def post_params
params.require(:post).permit(:text)
end
end
Problem:
User
Problem:
User
BUT
curl -d "user[name]=Charles"
-d "user[major]=EECS"
-d "user[age]=20"
-d "user[admin]=true"
http://localhost:3000/users
def user_params
params.require(:user).permit(:name, :age, :major)
end
curl -d "user[name]=Charles"
-d "user[major]=EECS"
-d "user[age]=20"
-d "user[admin]=true"
http://localhost:3000/users
def create
@user = User.new params[:user]
end
def create
@user = User.new user_params
end
private
def user_params
params.require(:user).permit(:name, :age, :major)
end
BECOMES
https://rubygems.org/gems
What did we learn today?
Individual Project - Due Friday, October 23rd