Skip to content

Instantly share code, notes, and snippets.

@jtallant
Last active December 12, 2016 19:28
Show Gist options
  • Save jtallant/0bea27e9a1625104146d42882abd84c2 to your computer and use it in GitHub Desktop.
Save jtallant/0bea27e9a1625104146d42882abd84c2 to your computer and use it in GitHub Desktop.
Mass Assignment

// app/views/users/edit.html.erb

<form action="/users/1" method="POST">
    <input type="hidden" name="_method" value="PUT"
    <input type="text" name="username" value="jtallant">
    <input type="email" name="email" value="justin.tallant@nycda.com">
    <textarea name="bio">Bio goes here</textarea>
</form>

When this form is submitted, the UsersController#update action will be called

The params will look like the following:

params = {
    username: 'jtallant',
    email: 'justin.tallant@nycda.com',
    bio: 'Bio goes here'
}

// app/controllers/user_controller.rb

class UsersController < ApplicationController
  def update
    @user = User.find(params[:id])

    if @user.update(params) # Mass Assignment
      flash[:notice] = "User successfully updated!"
      redirect_to('/users')
    else
      render('edit')
    end
  end
end
@user.update(params)

# is the same as...

@user.update({
    username: 'jtallant',
    email: 'justin.tallant@nycda.com',
    bio: 'Bio goes here'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment