Error adding custom route to controller - ruby-on-rails

I've rewritten my question to be more accurate. I have a bankaccounts controller / model.
I have the following method on my controller
def search
##ledgeritems = Ledgeritem.where("bankaccount_id = ? and transactiondate >= ? and transactiondate < ?", params[:bankaccount_id], params[:startdate], params[:enddate])
#bankaccount = Bankaccount.find(params[:bankaccount_id])
respond_to do |format|
format.js { render :partial => "bankaccount/bankledger" }
end
end
I've made two attempts to call this.
Attempt 1
Route for attempt 1
resources :bankaccounts do
post "search"
end
This shows the following route when I do a rake
bankaccount_search POST /bankaccounts/:bankaccount_id/search(.:format) bankaccounts#search
Javascript for calling attempt 1
$.ajax({
type: "POST",
url: "/bankaccounts/" + bank_account_id + "/search.js",
data: $('#edit_bankaccount_' + bank_account_id).serialize(),
success: function (result, status) {
$('#bank_ledger_div').html(result);
}
});
This calls the correct route on my controller, but the server sees it as a PUT instead of a POST and returns a 404.
Attempt 2
Route for attempt 2
resources :bankaccounts do
collection do
post "search"
end
end
This shows the following route when I do a rake
search_bankaccounts POST /bankaccounts/search(.:format) bankaccounts#search
Javascript for calling attempt 2
$.ajax({
type: "POST",
url: "/bankaccounts/search.js",
data: $('#edit_bankaccount_' + bank_account_id).serialize(),
success: function (result, status) {
$('#bank_ledger_div').html(result);
}
});
This calls the update route but still showing as a PUT command. In Firebug I see a 500 error with the following result
Couldn't find Bankaccount with id=search

Usually this error means you're making a GET request instead of a POST request.
For example:
GET /bankaccounts/search is assumed to be requesting the SHOW page for a bankaccount with ID = search
While
POST /bankaccounts/search would correctly hit your action.
Edit:
resources :bankaccounts do
collection do
post "search"
end
end
Is correct as well. Now I'm noticing that you are doing this to get your data:
data: $('#edit_bankaccount_' + bank_account_id).serialize()
that form likely has a hidden field in it, put there by rails, with name='_method' and value='PUT'. That is what is convincing rails that your POST is really a PUT. You'll need to remove that from the serialized data in order to correctly post the form.

If you want the /search url to be used without specifying an id, you should declare it as a collection action :
resources :bankaccounts do
collection do
post "search"
end
end
You can check the routes defined in your app with the rake routes command, to ensure that you defined what you meant.

The URL is expecting the format
/bankaccounts/:bankaccount_id/search
Is the error coming from this method? Could /bankaccounts/search be matching another route?

Related

How to get URL parameters from angularjs $location in Ruby on Rails?

I'm showing a database table using ruby on rails, and I'd like to sort the columns whenever I click on the column title.
My idea was to call an angularjs function that adds a parameter like ?sort_by=id to the url and get it back in my ruby controller to do the ordered request, but it seems like it's not working.
Here is the part of my users.html.haml file which calls the function :
%th
%button{'ng-click': 'sort_by("product")'}
My angularjs function (users.controller.js) :
$scope.sort_by = function(str){
$location.search({sort_by: 'product'});
$window.location.reload();
}
And index function in users_controller.rb
def index
#users = User.all
max_per_page = 50
puts params
paginate #users.size, max_per_page do |limit, offset|
render json: #users.limit(limit).offset(offset)
end
end
When I click on the button, it reloads the page with ?sort_by=product in the url and calls the index function, but puts params still returns {"subdomain"=>"admin", "controller"=>"admin/users", "action"=>"index"}
How can I make this work ?
Thanks in advance.
I used an $http get request with params and it finally worked, in case it helps someone :
$http({
method: 'GET',
url: 'users',
dataType: 'json',
params: {
'sort_by': 'products.name',
},
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
console.log('succes');
}).error(function(error){
console.log('err');
});
and then in index method in users_controller.rb :
puts request.params['sort_by'] if !request.params['sort_by'].nil?

ajax get data from a rails controller

I am trying to use ajax to get information from my controller. Basically I want to know if a data already exists in the DB or not, so my controller will return either true or false.
At the moment I am just trying to set the basic ajax call
in my js file I have the following ajax call, as you can see at the moment I am not really doing any logic because my data is just a placeholder. Later I will add the information I want to query
$.ajax({
type: "GET",
url: "/locations/exists",
dataType: "JSON",
data: { 'locition_exist': loc_exit },
success: function(data) {
console.log(data);
}
});
In my controller I have
def exists
location_exists = true
respond_to do |format|
format.html
format.json {render json: location_exists }
end
end
Later value will go into a method in the model that will query the DB and return true/false.
In my routes I have
resources :locations
get 'locations/exists', to: 'locations#exists'
This code results in the following error
The action 'show' could not be found for LocationsController
I am new to rails and ajax , and I based my code on different examples that I read here, so I am probably just doing a stupid noob mistake.
Thank you very much for your help
When using get or match in routes, you need to define the controller method mapped
get 'locations/value', to: 'locations#value'
update
You saw the same error after updating routes. There are two reasons of this error:
You defined resources :location at first. The url locations/exists itself matches "show" method within resources, with Routes taking 'exists' as the id in #show.
You have not defined show within LocationsController
So, Routes will firstly map the url to locations#show with the :id as 'exists', then hits the controller and found #show does not exist.
The solution after your updating
Of course you can put get 'exists'... before resources but that looks ugly.
Since 'exists' requires no id, it is a collection method. So you can use Routes built-in ways to do that.
resources :locations do
collection do
get 'exists'
end
end
By this all your resources and 'exists' can live.

rails ajax call redirect to invalid path

This is my ajax call
$.ajax({
type: "GET",
url: '/posts/product_list.json',
data: {sub_cat_id: parseNumber(sub_category_id)},
dataType: 'json',
success: function(data) {
//$('#selection').show();
$('#selection').html(data.html);
},
error: function(data){
}
});
I have the post_list controller
respond_to :json,only: :product_list
def product_list
#products = Product.where(sub_category_id: params[:sub_cat_id])
##blah blah blah
end
My url is showing like this while inspecting product_list.json?sub_cat_id=5
But the debugger is showing request parameter as follows
{"sub_cat_id"=>"5", "action"=>"show", "controller"=>"posts", "id"=>"product_list", "format"=>"json"}
I am very much confused why this is happening can any one clear it.
It appears you don't have a corresponding route entry. You should have something like this in your routes.rb:
resources :posts do
get :product_list, on: :collection
end
If you only specify resources :posts, your GET request would match the one for GET /posts/:id (look at the output of rake routes), i.e. show action of PostsController with product_list parsed as the id parameter in the request URI. get :product_list defined after those 7 entries would make the router match the URI to the corresponding action and controller.

How to insert into table using link tag

I have ArtistProduct model. User enters the product details, user can view the entered details in modal window by clicking the preview link before saving the details.
I'm trying to save the data using AJAX by passing all the details like params when it is validated, but it not saving the database.
In view I'm calling AJAX:
var theVal=id+'/'+artist_id+'/'+name+'/'+desc+'/'+price+'/'+story+'/'+artist_name+'/'+dimension+'/'+material+'/'+contact
var theURL = '/add_temp/' + theVal;
$.ajax({
url: theURL
});
In controller I'm handling it like so:
def add_temp
#pro_id=ArtistProduct.where("id=?",params[:id])
if #pro_id.nil?
#artistprod = ArtistProduct.new(:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[:price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:contact])
#artistprod.save
end
end
UPDATE
Thanks for your reply.
Now am getting Routing error.
In my Router I have like:
match 'add_temp/:id/:artist_id/:name/:desc/:price/:story/:artist_name/:dimension/:material/:contact'=> 'artist_products#add_temp'
UPDATE
Routing Error404 Not Found
No route matches [POST] "/add_temp/P58018/58/Prod/swsx/50/sfdf/null/null/0"
UPDATE
Ya i identified it and corrected it but still also values are not saving into the database. Please help me
In Controller i am doing like so:
def add_temp
if !(ArtistProduct.where("id=?",params[:id]).exists?)
#artistprod=ArtistProduct.new(:id=>params[:id],:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[:price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:contact])
#artistprod.save
respond_to do |format|
format.html { redirect_to #artistprod.addproduct }
format.js
end
end
end
Hi dbkooper, Thanks for your answer. I tried answer given by u but am getting Routing error
In view am calling like:
var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'product_name='+name+'description='+desc+'product_price='+price+'product_story='+story+'artist_name='+artist_name+'dimensions='+dimension+'material='+material+'contact_number='+contact;
The big problem I see is that your $.ajax call is missing some options. By default, $.ajax defaults to a GET request if no type is specified.
You should change it to:
$.ajax({
type: 'POST',
url: theURL,
success: function (json) {
// handle your success here
},
error: function (response) {
// handle your errors here
}
});
This way, you specify that it will be a POST request and you also have callback methods for handling success and error
I think your routes should be
resources artist_products do
member do
post 'add_temp'
end
end
use rake :routes to get the correct routes
most probab it will be "artist_products/:id/add_temp"
For ajax request it will be you can send the val param's using ? to the url
like
var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'so on..';
$.ajax({ url: theURL });
Inside your controller
you can access params as usual

Routing in Ajax petition in Rails 2

I have the following in my view:
$('#anID tr').click(function () {
$.ajax({
type: 'GET',
url: '/tickets/extended_info',
dataType: 'script',
data: { id: $(this).find('td:first').html() }
});
});
and this in my tickets controller:
def extended_info(id)
puts ">>>>>>>>>>>>>>> " + id.to_s
end
But I always get 404 not found from the ajax request.
I think I'm missing something in my routes file... I tried several things, but nothing.
Any ideas?
>>>>>>>>>>>>>>>>>>>>> RESOLVED <<<<<<<<<<<<<<<<<<<<<<<<<
I had to add:
map.extendedInfo '/extended_info/:id', :controller => 'tickets', :action => 'extended_info'
to my routes file.
Also, I was using "GET" in my ajax call in my JavaScript ... I changed to POST and now it's working =)
Really seems like routing trouble. Do you have appropriate row for /tickets/extended_info path in your routes.rb? If so, can you post it here?
I suppose something like this
get "/ticket/extended_info", :to => "tickets_controller#extended_info"
in routes.rb and your action on controller should be just
def extended_info
puts params[:id].inspect
end

Resources