This has confused me on several different occasions and each time I struggle to find a good answer on the Internet or the World Wide Web. Let's say that in my javascript file I have a variable
var myLoc = { lat: 35, lon: -110 }
that I got from using geolocation whatnot. I want to send this information to the backend in order to associate it with a specific post I'm going to create.
Assume my routes are just this:
resources :users do
resources :posts
end
I don't know if this is the correct way, but what comes to mind is something like this:
$.get('/users/' + JSON.stringify(myLoc) + '/posts/new', function() {console.log("please work")});
My questions are:
A. Should this work?
B. Is it the right way to do this?
C. Can you send front-end stuff like this to any route in the backend?
Much appreciated.
You can send information to a page with get
via the query-string, then this can be used to populate fields in the new
view which is where the form is that eventually submits to the create action.
However, this will also return the body of the new action view in the response, which you may want if you're using this to asynchronously pull that page in for a dialog or something.
It might be better, if you're using this ajax call to create a post, to post
to a /create
action on the posts controller.
Then you can send the data in JSON as a post
and the object will translate into the params
hash when your controller goes to parse it and create the post.
js in the view:
var url = '/users/' + userId + '/posts/create';
var myLoc = { 'lat': 35, 'lon': -110 };
$.ajax({
type: "POST",
url: url,
data: myLoc
});
in routes.rb:
match 'users/:user_id/posts/create' => 'posts#create', :via => :post
in posts_controller.rb:
def create
post = Post.new(params[:myLoc])
if post.save!
render :status => 200
else
# exception handling
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With