rest - Ruby on Rails: is using params.require() important? -


i'm trying create restful api simple web app made using ruby on rails. specifically, i'm trying implement post /users.json create new user.

the "parsing response json" bit handled scaffolding. issue comes when trying use strong parameters method scaffolded.

i make post request using postman chrome extension to:

   # post /users    # post /users.json    def create      user_params[:karma] = 1      @user = user.new(user_params)      respond_to |format|       if @user.save         format.html { redirect_to @user, notice: 'user created.' }         format.json { render :show, status: :created, location: @user }       else         format.html { render :new }         format.json { render json: @user.errors, status: :unprocessable_entity }       end     end   end  

so user_params called, , requires user (note method generated scaffolding):

def user_params   params.require(:user).permit(:name, :karma, :about) end 

i realised can work around "not requiring" user in params:

def user_params   params.permit(:name, :karma, :about) end 

but safe or appropriate? there more correct way?

and why user required in first place, if that's intend create?

params.require(:user).permit(:name, :karma, :about) 

says params hash must contain key called user , checks associated value contains named keys. aside security check, returns pretty params[:user]. requires params hash of form

{   :user => {     :name => "bob",     :about => "professional builder",     :karma => "10"   } } 

you'll parameters hash if field names in form / http request user[name], user[about], you'll if use rails form helpers

on other hand sounds parameters hash sending is

{   :name => "bob",   :about => "professional builder",   :karma => "10" } 

because in request field names name, about, karma.

the problem doing params.permit(:name, :karma, :about) stops ever passing other parameters action because parameter checker won't allow them (and if did allow them user.new complain).


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -