No route matches [POST] "/" when posting a form - ruby-on-rails

I'm trying to set up a form on my index page that will pass a param myform, to the same index page via a GET request. I thought this would be relatively simple. but I'm getting an error.
I generated a controller, RecipesController, with a method called index:
class RecipesController < ApplicationController
def index
#search = params[:myform]
return #search
end
end
In this method I'm trying to get back what the user types into a textbox when a button is pressed and the GET request is fired.
Here is my view:
<h1>Recipe Finder</h1>
<%= form_tag(controller:"recipes",method:"get") do %>
<%= label_tag(:myform, "Search") %>
<%= text_field_tag(:myform) %>
<%= submit_tag("search") %>
<% end %>
Here are my routes:
Rails.application.routes.draw do
root 'recipes#index'
This shows up fine when I visit localhost:3000, but when I press the button I'm expecting the controller index method to just return whatever text i typed into the textbox. Unfortunately, I only get:
No route matches [POST] "/"
I know setting the root to recipes#index is causing the failure as my #search variable is not set when the page is opened initially.
I'm wondering if I should have a separate route and method for the GET request and should I just open the main page with the call to localhost:3000 without running any code in the controller? Is this possible?

The problem is that form_tag accepts a Hash as both its first and second argument. If you don't use brackets, it's going to interpret all of it as part of the first argument, and your method: "get" is not applied properly.
Because of this, it defaults to doing a POST request, for which there is no route.
Try this. Because the first argument is no longer a Hash, it should work properly:
<%= form_tag("/", method: "get") do %>
Alternatively, using your code, you can try this:
<%= form_tag({ controller: "recipes" }, { method: "get" }) do %>

Related

Get rails route to reflect database lisiting

I currently have a page that searched through a listings database. On clicking a selection, the view links to that listing's show page:
<div class="listings_wrapper">
<% #listings.each do |listing| %>
<%= link_to listing_url(listing), class: "listing_link" do %>
<div class="listing">
<div class="picture">
<% if listing.thumbnail != nil %>
<%= image_tag(listing.thumbnail, class: "list_image") %>
<% end %>
</div>
The show page that is currently routed as:
get 'listings/:listing_id', to: 'listings#show', as: 'listing'
which will get me the address
localhost3000/listing/612983618 (arbitrary id)
What I'm trying to do is get the route to display information from the database in the route instead, for SEO purposes:
localhost3000/listing/[address]/[booking_id]
When I try to adjust to
get 'listings/:listing_id', to: 'listings#show', as: 'listing/:address/:booking_id'
I get blocked on loading. I've been looking around stackoverflow at similar answers, but haven't got my head around this problem as of yet. Since the link is pulling the object itself, and the route is pulling the id from that, it would make sense to refer to the :address key instead, but something is clearly missing. Help?
In order to make the URI for listings#show to receive the address and booking_id of the object, then you could move the alias in your route definition to the uri argument, like:
get 'listing/:address/:booking_id', to: 'listings#show'
Now it'll be waiting both attributes. While in your controller if you want to find that specific object from both sent attributes, then you can use find_by:
#listing = Listing.find_by(adress: params[:address], booking_id: params[:booking_id])
#listings = Listing.last(3)
Note this will work, but in case you have more than one record with same address and booking_id, find_by will just return the first one.

Rails: flash message shows in the url as param

Hi all my flash messages work in the normal fashion but there is an action in one of my controllers where the flash message does not work.
This is the view:
<%= form_tag update_status_order_path(update_status), method: :put do |f| %>
<%= select(:order, :status, [['Active', 1], ['Inactive', 0]]) %>
<%= submit_tag "Update" %>
<% end %>
This is the controller action
def update_status
if #order.update_order_status! params[:order][:status]
redirect_to show_orders_ofert_path #order.ofert, success: "Updated!."
else
redirect_to show_orders_ofert_path #order.ofert, error: "Error."
end
end
When I send the form the action is performed correctly, but the flash message is not displayed in the layout, instead is displayed in the url as a param, just after click the Update button it reloads and shows the url like this:
http://localhost:3000/oferts/48/show_orders?success=Updated!
I have tried changing put to patch but it did not worked, even changing the action to work with respons_to block but it did not work, any idea?
this problem is only happening with that specific action because with the other actions I have the flash messages are isplayed normally.
Thanks
The success and error keys are being used as parameters to the show_orders_ofert_path because there are no parenthesis. Add parenthesis around the path helper arguments:
redirect_to show_orders_ofert_path(#order.ofert), success: "Updated!."

404 error when making an ajax call to controller from view in rails for dynamic drop down select

I am trying to dynamically populate a select list and I am getting a 404 error when I make my ajax call to my controller. I have looked around but cannot find out why I am getting this error.
My controller where the method I want to call is.
class UsersController < ApplicationController
def index
##users = User.all
myList = [["A",1],["B"],2]
#classList = myList
render "index.html.erb"
end
.
.
.
def changeclasses
#classlist = [["B",2]]
end
end
And this is my view
<%= form_for UnoClass.new do |f| %>
Department: <%= select_tag(:city_id, options_for_select([['Accounting', 'ACCT'], 2),
{ id: 'departSelect'}) %>
<br />
Course : <%= select_tag(:course, options_for_select(#classList)) %>
<br />
Section : <%= f.text_area :section %>
<br />
<%= f.text_area :sessionId, value: request.session_options[:id], style: "display:none;" %>
<%= f.submit %>
<% end %>
<script>
$(document).ready(function() {
$('#departSelect').change(function() {
$.ajax({
url : "/changeclasses"
});
});
});
</script>
and my routes.rb
Rails.application.routes.draw do
resources :uno_classes
resources :users
root :to => 'users#index'
get '/changeclasses' => "users#changeclasses"
This is the error that I grab from the developer tools on chrome.
GET http://localhost:3000/changeclasses 404 (Not Found)
So, when I make a change to the upper select box departSelect, it makes a call to changeclasses but it cannot find it.
Also when I do rake routes the correct route shows up.
changeclasses GET /changeclasses(.:format) users#changeclasses
I have not implemented the method yet but it should change the #classList and therefore change the contents of the course select box and it never gets called because of the 404 error.
Any help would be appreciated because I cannot figure out why there is a problem here.
Here's some ideas on things you can try to get it working.
First. Create a view called "changeclasses.js.erb" in your Users views folder which is what Rails will by default look to load unless you tell it otherwise since its a js request. You can/should also put the js that you want to run with this particular method in that file (changeclasses.js.erb).
Second. Try updating the ajax call's datatype to "script" so that it will be processed by your controller as js.
$.ajax({
url : "/changeclasses",
dataType: "script"
});
Third. If all that doesn't fix it, I would add the below code to your controller to make it sure it is responding to js requests.
class UsersController < ApplicationController
respond_to :js
Hope one of those helps!

Fire up custom action when user clicks 'Search" on RAILS 3.2 form?

Is it possible to fire up an custom action when user clicks 'Search' button on search form?
There is an mechanism in our app to save every URL the app has hit. In our search form, when clicking 'Search' button, there will bring up the search result page. The problem is that the URL for the search result form was not saved. The Back button brings back the search page (for setup search params) instead of the search result page (because its URL was not saved).
Here is the search form for model configs:
<h4>Search Form></h4>
<%= simple_form_for #config, :method => :get, :url => search_result_configs_path do |f| %>
<%=render :partial => 'search_params', :locals => {f: f} %>
<%= f.button :submit, t('Search') %>
<% end %>
The URL for the search result looks like this (with the search params set by user) after user clicks Search button:
http://localhost:3000/configs/search_results?utf8=%E2%9C%93&engine_config[start_date_s]=&engine_config[end_date_s]=&engine_config[engine_id_s]=1&engine_config[argument_name_s]=&engine_config[commissioned_s]=&commit=%E6%90%9C%E7%B4%A2
This is the URL we would like the app to remember. We figure we need custom action triggered when a user clicks 'Search' button. Is it possible?
Route
Firstly, calling a custom application is actually quite a simple process - you just need to call its route:
#config/routes.rb
resources :search do
collection do
get :custom_action
end
end
This will allow you to use the likes of form_tag to call the custom route:
#app/views/your_controller/view.html.erb
<%= form_tag search_custom_action_path, method: :get do %>
...
<% end %>
--
Form
Secondly, you're using simple_form for your search form.
This is completely fine, but the problem you have here is that when you use this, it has to have a ActiveRecord object to populate the form with. This is probably where you're getting confused, as to do this, you need ot make sure #config is available every time you load that form, which I imagine can be a lot.
We've created a search form here:
Although in Rails 4, we used a form_tag for this form, as it allowed us to create & display the form where-ever we need in the app. This allows us to pass the required params through the form & access them on the other side
--
Params
You mention you want to "save the URL" - what do you mean by this?
Surely you'd prefer to save the params?
If this is true, the way to do this is actually relatively simple - you'll get access to the params hash in your controller when you send the request through:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def custom_action
params[:your_param] #-> this is accessible here
end
end
The bottom line is if you wanted to save the query strings, you'll have to create a model called Search or similar, allowing you to pass the params through when you process the custom action in your controller, just like you would any other ActiveRecord object

routing scope problem with form_for (partial)

Trying to route:
scope :shortcut do
resources :text_elems
end
Using basic scaffold with form partial
*_form.html.erb*
<%= form_for(#text_elem, :shortcut => #shortcut) do |f| %>
...
Problem is: When I call the edit action, the form html shows as:
<form ... action="/25/text_elems/25">
Note: The new action renders the form action correctly:
<form ... action="/home/text_elems">
So it appears that my :shortcut param is getting trumped by the :id param when form_for processes it's block. Now I am able to get the action to correctly route with the :shortcut param if I manually make the :url => {...} in the form_for block, but I would prefer to keep the code dry, plus I want to report this problem to rails if it is indeed a bug.
Can anyone else confirm this as a bug?
Actually, you can pass the values as a full hash, rather than trying to rely on the default to_param (which is what gets called if all you do is pass the #text_elem)
<%= form_for({:id => #text_elem.to_param, :shortcut => #shortcut}) do |f| %>
however, if this is actually a nested-resource, you could also do:
<%= form_for([#shortcut, #text_elem]) do |f| %>
I was having the same issues and none of the above answers helped.
The last answer on this page worked for me though...
https://rails.lighthouseapp.com/projects/8994/tickets/6736-problem-with-scoped-routes-and-form_for-helper

Resources