Params array being replaced by controller and method - ruby-on-rails

Im trying to retrieve the post parameters in my RoR app. However when i print:
params
It responds with
{
"action":"new",
"controller":"question"
}
Which is simply the controller and action.. How do i reference the post variables from the controller?
In my log, im getting the error: WARNING: Can't verify CSRF token authenticity

That is how you get post variables. If they're not there then there's a problem with your form or whatever is making the request.

Ditch your custom route match "/new/question" => "question#new", :via => :post You don't need it and it's just confusing matters. new actions don't accept params and should ONLY respond to GET requests.
Just send an HTTPPOST request to your/url/questions and rails will know to call the create action and you can pass in whatever params you need.
The new action is for rendering a form not for accepting POST requests.
Likewise if you send a PUT request to your/url/questions rails just knows to call the update action in the questions controller. That's the whole point of RESTfull routes.

Dude, are you including the "csrf_meta_tags" in your layout?
<%= csrf_meta_tags %>
If not, then rails will ditch all POST parameters...

Related

How can I hide params in view's url?

I'm passing a change id as a parameter with a link_to:
<%= link_to 'Change', my_service_path(change: '1234567890'), method: :get%>
In the controller I have:
def my_action
if params[:change]
...
params.delete :change
end
But when the view is displayed I still see
<view url>?change=1234567890
How do I prevent ?change=1234567890 from showing in the url?
That's because params is an instance of ActionController::Parameters, which was specifically created because people were treating the params object as a hash, as you're attempting to do.
As #arieljuod suggested, you'll have to convert your route/link to use a POST request instead of a GET request. That way the params will be sent along with the HTTP headers instead of showing up in the URL bar as a query string.
So in your case:
<%= link_to 'Change', my_service_path(change: '1234567890'), method: :post %>
...and make sure your route is configured to respond to a POST request
What you're trying to do, "Change", says to me you're trying to modify the state of a resource. In RESTful design, you should be PATCHing, not GET'ing.
The way you'd hide the params is to create a form, put change in a hidden field, and submit the form as a PATCH request using a button_tag.
In Slim, it would look like this:
= form_tag(url: my_service_url, method: :patch) do
= hidden_field_tag(:change, "123456789")
= submit_tag("Change")
On your website, it will look just like a regular link - but instead you are instructing the Rails server to EDIT the resource, not GET it.
to answer your question in the comments:
How will use of POST or a form prevent the query parameters from showing in the > url?
If you send a POST request, your request will have a body, too. So in the GET request from your link will send the change information via the url. In a POST request (use button_to or form) it will send via the body and not displayed in the url. You can then still access it via the params

Access old get parameters in URL after a post request

I have a form in RoR with a controller action that looks up a record via the get parameter.
def respond
if request.post?
# Submit logic here...
# cannot lookup this way to fill the form out again
# #current_message = Saved_message.find_by_id(params[:msg_id])
elsif request.get?
#current_message = Saved_message.find_by_id(params[:msg_id])
end
end
I can't use the params[:msg_id] to lookup the message again because it's a post request and I don't resend the get parameters. However, the get parameters remain in the url such as .../messages/respond?msg_id=2. I can get around this by passing in a hidden field with a different parameter name like <%= form.hidden_field :msg_id_2, value: params[:msg_id] %>. Then I can lookup the #current_message via the params[:msg_id_2]. However, I don't like this solution. Any advice to access the now inaccessible get parameter?
you should use RESTful routes so that you do not have to care about such issues.
since you are not posting much about the actual code or problem you are trying to solve, i can just assume what might be the issue here and how to solve it.

How does the params method work?

I have been trying to figure out how the params method works and I'm a bit stuck on the process.
For example, if a user clicks on a certain blog post in the index page, I guess that the link_to method calls the Post controller and the show action along with its block #post = Post.find(params[:id]) and then goes to the database to find the post and the view displays it.
So my missing link seems to be when is the post id passed into the params method?
Because the others already explained about params, I'm just going to answer directly a question of yours:
when is the post id passed into the params method
I think it's best explained with an example; see below:
say that you clicked a link:
/posts/1/?param1=somevalue1&param2=somevalue2
The Rails server receives this request that a client wants to view this GET /posts/1/?param1=somevalue1&param2=somevalue2 address.
To determine how the Rails server will respond, the server will first go to your routes.rb and find the matching controller-action that will handle this request:
# let's say your routes.rb contain this line
# resources :posts
# resources :posts above actually contains MANY routes. One of them is below
# For sake of example, I commented above code, and I only want you to focus on this route:
get '/posts/:id', to: 'posts#show'
From above notice that there is this :id, Rails will automatically set params[:id] to the value of this :id. This is the answer to your question where params[:id] comes from.
It doesn't have to be :id; you can name it whatever you want. You can even have multiple URL params like so (just an example):
get /users/:user_id/posts/:id which will automatically set the value on params[:user_id] and params[:id] respectively.
In addition to this URL params like :id, Rails also injects values to params[:controller] and params[:action] automatically from the routes. Say from the example above, get '/posts/:id', to: 'posts#show', this will set params[:controller] to 'posts', and params[:action] to 'show'.
params values also comes from other sources like the "Query string" as described by Mayur, and also comes from the body of the request, like when you submit a form (the form values are set within the body part of the request) and like when you have JSON requests, which all of these are automatically parsed by Rails for your convenience, so you could just simply access params and get the values as you need them.
Params are hashes in ruby with Indifferent access which means,
hsh = {"a" => 1, "b" => 2}
Consider this hsh as params returned from a POST request from browser, it's a key value pair with keys as string. Since it's a params so the values can be accessed as
hsh["a"]
=> 1
hsh [:a]
=> 1
params are formed on the client where the interface load, consider a form which has a submit button. When you press submit, the data filled in form or any hidden textboxes are formed into a hash and passed across the request. This when received on server end will be called as params or request params.
For Get requests: data send across the url will be read as params on backend.
GET: http://www.abx.com?user=admin
params on backend: {"user" => "admin"}
This will be displayed in rails server logs
For Put request: data send across the body will be called params.
PUT: http://www.abx.com
data: {"user" => "admin"} Client side
params on backend: {"user" => "admin"}
This will be displayed in rails server logs
How does the params method work?
The params come from the user's browser when they request the page. For an HTTP GET request, which is the most common, the params are encoded in the URL. For example, if a user's browser requested
http://www.example.com/?post=1&comment=demo
then params[:post] would be "1" and params[:comment] would be "demo".
In HTTP/HTML, the params are really just a series of key-value pairs where the key and the value are strings, but Ruby on Rails has a special syntax for making the params be a hash with hashes or array or strings inside.
It might look like this:
{"post"=>"1", "comment"=>"demo"}
Link to Rails Guides on params: guides

Form url not showing properly in rails

I have this URL for my edit form :
<%=form_for #cad,:url =>{:action => "update",:controller => "cad" } do |f| %>
And it should point to "/cad/update",but the URL is pointing to "cad/6".
Please help.
Thanks in advance
it's perfectly fine if you follow restful routes for update it's a member route
There are 2 types of route
first one is collection route which will work on in general for all object like index action and second one is member route which will work on specific object like show,edit,update,destroy etc ,
In your case update is member route it has http verbs is put and it's basically post request
you can check http method
and You don't need url hash on form rails pick it routes based on object

Identify GET and POST parameters in Ruby on Rails

What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP?
You can use the request.get? and request.post? methods to distinguish between HTTP Gets and Posts.
See http://api.rubyonrails.org/classes/ActionDispatch/Request.html
I don't know of any convenience methods in Rails for this, but you can access the querystring directly to parse out parameters that are set there. Something like the following:
request.query_string.split(/&/).inject({}) do |hash, setting|
key, val = setting.split(/=/)
hash[key.to_sym] = val
hash
end
You can do it using:
request.POST
and
request.GET
There are three very-lightly-documented hash accessors on the request object for this:
request.query_parameters - sent as part of the query string, i.e. after a ?
request.path_parameters - decoded from the URL via routing, i.e. controller, action, id
request.request_parameters - All params, including above as well as any sent as part of the POST body
You can use Hash#reject to get to the POST-only params as needed.
Source: http://guides.rubyonrails.org/v2.3.8/action_controller_overview.html section 9.1.1
I looked in an old Rails 1.2.6 app and these accessors existed back then as well.
There is a difference between GET and POST params. A POST HTTP request can still have GET params.
GET parameters are URL query parameters.
POST parameters are parameters in the body of the HTTP request.
you can access these separately from the request.GET and request.POST hashes.
request.get? will return boolean true if it is GET method,
request.post? will return boolean true if it is POST method,
If you want to check the type of request in order to prevent doing anything when the wrong method is used, be aware that you can also specify it in your routes.rb file:
map.connect '/posts/:post_id', :controller => 'posts', :action => 'update', :conditions => {:method => :post}
or
map.resources :posts, :conditions => {:method => :post}
Your PostsController's update method will now only be called when you effectively had a post. Check out the doc for resources.
I think what you want to do isn't very "Rails", if you know what I mean. Your GET requests should be idempotent - you should be able to issue the same GET request many times and get the same result each time.
You don't need to know that level of detail in the controller. Your routes and forms will cause appropriate items to be added to the params hash. Then in the controller you just access say params[:foo] to get the foo parameter and do whatever you need to with it.
The mapping between GET and POST (and PUT and DELETE) and controller actions is set up in config/routes.rb in most modern Rails code.
I think what Jesse Reiss is talking about is a situation where in your routes.rb file you have
post 'ctrllr/:a/:b' => 'ctrllr#an_action'
and you POST to "/ctrllr/foo/bar?a=not_foo" POST values {'a' => 'still_not_foo'}, you will have three different values of 'a': 'foo', 'not_foo', and 'still_not_foo'
'params' in the controller will have 'a' set to 'foo'. To find 'a' set to 'not_foo' and 'still_not_foo', you need to examine request.GET and request.POST
I wrote a gem which distinguishes between these different key=>value pairs at https://github.com/pdxrod/routesfordummies.
if request.query_parameters().to_a.empty?

Resources