How do you handle RESTful URL parameters in a Ruby on Rails application?

I am dealing with a very simple RESTful Rails application. There is a user model, and I need to update it. Rails codes like to do:

if @user.update_attributes(params[:user])
...

And from what I understand in REST, this url should work:

curl -d "first_name=tony&last_name=something2&v=1.0&_method=put" http://localhost:3000/users/1.xml

However, it is obvious that this will not work, because each URL parameter will parse the variable "params", not "params [: user]"

I have a hacker fix, but I wanted to know how people usually deal with this.

thank

+3
source share
2 answers

, Rails . , . - :

curl -d "user[first_name]=tony&user[last_name]=something2&v=1.0&_method=put" http://localhost:3000/users/1.xml

{:user=>{:last_name=>"something", :first_name=>"tony"}}

params. , Rails - params, name.

+4

; URL-, /. URL-, / ( ).

, :

class User < ActiveRecord::Base

  #class method
  def self.new_from_params(params)
    [:action, :method, :controller].each{|m| params.delete(m)}
    # you might need to do more stuff nere - like removing additional params, etc
    return new(params)
  end
end

:

class UsersController < ApplicationController
  def create
    #handles nice and ugly urls
    if(params[:user]) @user=User.new(params[:user])
    else @user = User.new_from_params(params)
    end

    if(@user.valid?)
    ... etc
    end
  end
end

, , .

, , " " URL- (.. , ).

+3

Source: https://habr.com/ru/post/1733708/


All Articles