10.1 updating users.
1. git checkout -b updating-users
?
2. in this chapter, we will make you can update user profile.
a. we will use a "edit" action to render a view to edit user.
b. we will use "update" action and a "PUT" request to update user profile
c. we need to make sure only current user can update their information. this need a "before_filter"
?
3. edit form, we will start from TDD again!!
?
?4. now it is time to write the view code:
?
? . . .</form>?
note this hidden line:
?
since web browser can't natively send "PUT" request, rails fake it with a post request, and a hidden input field.
?
6. there is another magic that you may wondering,
?
we use the same code for edit form and new form, but why the html generated are different?
for new action, rails use a post method, and for edit action, rails use a put method.
?
the answer is simple and trikey, rails will run
?
@user.new_record?
?
to judge if this record is a new one, or already exist in database.
?
so rails will know to use a put request or post request, clever?? cool!
?
7. next is the test for update success and update failure.
?one thing to note:
?
@user.reload ?========> this will reload the @user content from database.
?
8. next, we will implement the update method in the controller:
?
def update @user = User.find_by_id(params[:id]) if @user.update_attributes(params[:user]) flash[:success] = "Profile updated" redirect_to @user else @title = "Edit user" render 'edit' end end?