I have a method where i am redirecting it to another action. Here's the code:
def redirectPage (String appNum) {
redirect(action: "showMan")
}
Now, once this the navigates to another page the URL will appear as http://myserver/myapp/showMan
I want this URL to appear as http://myserver/myapp/showMan?SomeIdentifier
I actually want to append this ID to the end of the page ?SomeIdentifier . How can i do it?
Use the param attribute of redirect according to the official documentation.
redirect(action: 'showMan', params: [param1: 'value1', param2: 'value2'])
This will result in
http://<host>/<your-app>/<controller>/showMan?param1=value1¶m2=value2
Related
I'm trying to pass a url string to a view from one of my controller methods, like so:
def index
#locals = {table_cols: $config['global_fields'],
table_title: $config['main_page']['table_title'],
ajax: url_for(action: index_data)}} # HERE
end
index_data is a function in my controller that returns some data in JSON format. However, when I navigate to the index page of my application, the browser simply displays the JSON output of index_data.
I'm assuming calling url_for within index is redirecting that page to index_data - is there a way to prevent this and just have url_for return the string, e.g. '/controller/index_data'?
Thanks
It's probably because you are calling the index_data action when you attempt to get a url to it, and calling it is tricking Rails into thinking you want to render from that action.
If you change your url_for to point to a symbol (or string) instead of the return value of the action, things will probably start working as you expect:
#locals = { ..., ajax: url_for(action: :index_data)}}
In my jobsController, I have a method named getEmployee(). This method renders view named employee.gsp.
render(view : "employee")
When my view is displayed, the url is generated as given below.
http://localhost:8080/test/jobs/getEmployee
Now in this URL I want to append a parameter pagination=false. So my new url should look like:
http://localhost:8080/test/jobs/getEmployee?pagination=false.
How can I do this? Is there any way to append parameters in the generated URL from the controller method getEmployee?
there is a trick to do so, by redirecting to getEmployee action with params.pagination = false
redirect action:'getEmployee', params:[pagination:false]
for example
assume I want 'x' parameter in my /cont/checkGet?x=false like this, so I will redirect from 'check' action to 'checkGet' action with x params
def check(){
redirect action:"checkGet",params: [x:false]
}
def checkGet(){
render "Anshul"
}
hope this helps, Thanks
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
When a user is creating a new Load object, if the user checks the "Paid On Delivery" check box then they will be redirected to the Payment controller immediately after the new Load has been created. Several of the parameters needed to create a new Load are also used to create a new Payment, so I just pass the parameters in the redirect like this:
redirect(controller: "payment", action: "create", params: params)
This works fine, but it gives me a real nasty URL with all the parameters in it. How can I pass my parameters to another controller and keep them from appearing in the URL?
UPDATE:
I should say that I appreciate everyone's suggestions for such a little problem. Even with all the suggestions, it still seems the best way of doing this is the way I wanted to avoid, building the parameter map manually in the redirect call. It isn't that big of a deal, especially since there is only a few params, I just don't believe there is isn't a cleaner more automated way of fixing this.
def loadInstance = new Load(params)
if (loadInstance.save(flush: true)) {
Account.get(params.account.id).balance -= new BigDecimal(params.transactionAmount)
flash.message = "${message(code: 'default.created.message', args: [message(code: 'load.label', default: 'Load'), loadInstance.id])}"
if(params.paidOnDelivery){
redirect(
controller: "payment",
action: "create",
//There has to be a better way than this. Just writing "params:params" results in the values being wrapped in double quotes once they get to the Payment controller. If it wasn't for that then "params:params" would work great and I would not of had to ask this question :)
params: [
"account.id":params.account.id,
"dateOfTransaction":params.dateOfTransaction,
"dateOfTransaction_year":params.dateOfTransaction_year,
"dateOfTransaction_month":params.dateOfTransaction_month,
"dateOfTransaction_day":params.dateOfTransaction_day,
"dateOfTransaction_hour":params.dateOfTransaction_hour,
"dateOfTransaction_minute":params.dateOfTransaction_minute,
"transactionAmount":params.transactionAmount
]
)
return
}
redirect(action: "show", id: loadInstance.id)
}
else {
render(view: "create", model: [loggedByUsers:loggedByUsers, accounts:accounts, cargoProviders:cargoProviders, deliveredByUsers:deliveredByUsers, loadInstance:loadInstance])
}
You could do a server-side forward instead of a redirect. Simply replace:
redirect(controller: "payment", action: "create", params: params)
with:
forward(controller: "payment", action: "create", params: params)
Update
To fix the refresh problem you described in the comments, make the action that you forward to sends a redirect (instead of rendering a view), e.g.
class PaymentController {
def create = {
Integer paymentId = // Create a payment and get it's ID
redirect(action: 'show', id: paymentId)
}
def show = {
def id = params.id
// show the payment with this ID
}
}
Pass them via session parameters
or
Make the HTTP request server-side instead of a redirect and then just render the result to the client
The flash object can be used to achieve this (although I would leave the implementation as is).
Copy all your params to flash.
params.each {
flash[it.key]=it.value
}
Use the flash map instead of params map in the 'create' action.
i didn't try it but i think it will solve your problem.
redirect(controller: "payment", action = [POST:"create"], params: params)
Here's another suggestion :-)
Keep the redirect from Load to Payment as is. Check in Payment action if you receive a call with params, then save those in session or flash and redirect to same action without params. Restore params from session/flash using putAll and proceed with action.
Kind of like a Post-Redirect-Get in Payment, but actually a GetWithParams-Redirect-Get. Results in clean URL and no Refresh problems.
I use it in a app for clean URLs and for keeping states in different parts of the app (but since you don't need the latter you should remove it or keep it in flash).
My user experience involves users submitting a form before they've authenticated (using omniauth). I started doing something like this:
def self.require_facebook_authentication!(options={})
before_filter :redirect_to_facebook_if_not_authenticated options
end
def redirect_to_facebook_if_not_authenticated
if !logged_in?
session[:param_cache] = params
session[:original_destination] = request.fullpath
redirect_to '/auth/facebook'
end
end
Then, on hitting the auth callback, redirect to a page that submits a form with the post params inline, for a total of 3 redirects (/stuff/new/ on POST -> auth/facebook -> facebook -> /auth/facebook/callback [ html template with POST form ] -> /stuff/create). I'd rather not create an authentication popup; instead, I'd like to navigate to a separate page, log in, and redirect to the completed action.
I'm fairly new to Rails, so I'm still learning - is this already built in to another framework? Am I missing something really basic? Thanks in advance!
if you are asking as to whether or not there is a "RAILS" way that will automatically post the data after a redirect, the answer is no (see https://stackoverflow.com/questions/985596/redirect-to-using-post-in-rails)
In my opinion the safest, easiest, and most RESTful way to achieve what you want would be to simply have the params you are eventually posting stored in session so that you can redirect back to the original 'new' page and have the form automatically prefilled with the post data. Sure this is one extra step for the user, but since REST doesn't allow for redirects to POSTs it is imo the cleanest way to go about it
There may be a better way, but if you render this after authenticating, then the client will Ajax post the form contents then redirect.
<script>
new Ajax.Request(<%= session[:original_destination] %>, {
method: 'post',
params: '<%= session[:param_cache].to_query %>',
onSuccess: function(){
window.location = '<%= session[:original_destination] %>';
}
});
</script>