Call "create" action of a controller - ruby-on-rails

I created a controller, using Rails 3 generator "Controller", and only two actions: create and destroy.
So it generates for me these two lines in routes.rb:
get "mycontroller/create"
get "mycontroller/destroy"
First I change these action to POST and DELETE verbs:
post "mycontroller/create"
delete "mycontroller/destroy"
And I'm using jquery to call these actions, like this:
Calling ˜create˜:
$.ajax({
type: "POST",
dataType: "script",
data:{id: id},
url: "/mycontroller"
})
but it's not working. I need to put "/create" in the url to work:
$.ajax({
type: "POST",
dataType: "script",
data:{id: id},
url: "/mycontroller/create"
})
What is wrong?

Related

Rails 5: ajax post request not working correctly

I'm currently trying to add a form to my homepage. The survey calculates the needed impressions based on the user input.
The problem is that when I pass the value impressions for example 200 to ajax, it sends a POST request back to the form, but there I have #impressions = params[:impressions] which is nil.
Since #impressions = params[:impressions] already exists with the GET request. The POST request isn`t even showing up in the console.
Ajax code:
$.ajax({
data: 'impressions=' + impressions,
dataType: 'script',
type: 'POST',
url: "/pages/home"
});
Routes:
root to: 'pages#home'
post '/pages/home' => 'pages#home'
PagesController home:
protect_from_forgery :except => [:home]
def home
#impressions = params[:impressions]
end
What would be the right soultion? Probably I should set #impressions = 0 and change the ajax request from POST to PUT ?
Maybe format your Ajax request as Json?
$.ajax({
data: {impressions: impressions}
dataType: 'json',
type: 'POST',
url: "/pages/home"
});
Try below method.
$.ajax('/pages/home', {
type: "POST",
data: 'impressions=' + impressions,
dataType: 'script'
})
Hope this helps!!

Not getting form data sent via ajax post request rails

I am trying to send my form data which includes some text fields and one image field to controller via ajax post request.
The form data looks like this:
And this is the ajax call i am making
$.ajax({
type: "POST",
dataType: "json",
processData: false,
data: {'new_post_data': data},
url: "/posts/newpostcreate",
success: function(resp, status){
}
});
The request is being sent but in the controller I am getting something like
ActionController::Parameters {"object Object"=>nil, "controller"=>"posts", "action"=>"new_post_create"} permitted: false>
I have spent many hours looking for a solution and trying different solutions but still it does not work. I'm not getting what I am missing.
Looks like you are using the wrong format and that your 'data' variable is empty (hint given in the Params: "object Object"=>nil). Try passing this:
$.ajax({
type: "POST",
dataType: "json",
data: { new_post_data: "test" },
url: "/posts/newpostcreate",
success: function(response){
console.log(response);
}
});
Edit: I realized you have a file attachment in your data. I think your safest bet is to create a FormData object and assign all your data to it.
https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
I am not sure about processData: false. I never used it.

Rails sending duplicated/wrapped parameter

I create in my coffeescript code an object to pass via ajax post request which looks like this:
{"Category":[{"value1a":"v1a", "value2a":"v2a"}, {"value1b":"v1b", "value2b":"v2b"}]}
Via this code
$.ajax({
url: 'master/create',
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(tickets)
})
tickets is the name of the object made.
but Rails is interpreting this like
Parameters:
{"Category"=>
[{"value1a"=>"v1a", "value2a"=>"v2a"}, {"value1b":"v1b", "value2b":"v2b"}],
"master"=>
{"Category"=>[{"value1a"=>"v1a", "value2a"=>"v2a"}, {"value1b":"v1b", "value2b":"v2b"}]
}
}
Where is this "master" coming from, and why is this happening?
If it helps, master is the name of the controller.

How to use a rails route for a singular resource in my javascript ajax?

Currently I have the following (working) code:
# app/assets/javascripts/show_group_members.js.erb
...
var gid= $(this).data("id");
...
$.ajax({
type: "GET",
url: "/groups/"+gid,
contentType: "application/json; charset=utf-8",
dataType: "json",
...
but I would like to use the routes for a single group resource, i.e.
group GET /groups/:id(.:format) groups#show
So I am trying to use
url: <%= Rails.application.routes.url_helpers.group_path %> + gid,
but I am getting
No route matches {:action=>"show", :controller=>"groups"}
missing required keys: [:id]
(in /home/durrantm/.../linker/app/assets/javascripts/show_group_members.js.erb)
[Update]
The complication here is that the view content itself is generated by a .js.erb template so I still can't use group_path(group) in it.
How can I use the route in js when there is a resource ?
btw I also tried
url: <%= Rails.application.routes.url_helpers.group_path %>,
data: { id: gid },
I think you are doing it wrong. I would forget about placing Rails code into the js and pass the url with data. Thanks to this you separate your Rails code from JS and avoid issues during assets compilation (like what is the host when no request is made?).
# view
<span data-link-url="<%= group_path(group.id) %>"></span>
# js
var link = $(this).data("link-url");
...
$.ajax({
type: "GET",
url: link,
contentType: "application/json; charset=utf-8",
dataType: "json",
...
Using <a href="your_link_to_group_here">
<%= link_to 'my link', group_path(group.id) %>
var link = $(this).attr('href');
Another way to do it, is to use js-routes.
Install the gem:
gem "js-routes"
Include it in your application.js file:
/*
= require js-routes
*/
Then you can do this:
# app/assets/javascripts/show_group_members.js
...
var gid= $(this).data("id");
...
$.ajax({
type: "GET",
url: Routes.group_path(gid),
contentType: "application/json; charset=utf-8",
dataType: "json",
...
The routes helper still needs the resource to be passed to it, even if it's a singular resource. So, your route should look like
Rails.application.routes.url_helpers.group_path(group)
group being the variable where you store your ruby object.
Although, personally, I prefer #konole 's approach.
Because of the complication that the HTML is, itself generated by js (i.e. I get the list of links for the group when I click the 'members' link, via ajax.
So in the end I used:
...
url: "<%= Rails.application.routes.url_helpers.groups_path %>" + "/" + gid,
...

Which type of Ajax should I post to a Rails 3.1 controller when creating records?

I have a newsletter box that submits via ajax like this:
function ajax_subscribe(){
$.ajax({
url: '/subscribe',
type: 'post',
data: ({
email: $('#email').val()
}),
success: function(msg){
$('#newsletter_form').hide();
$('#newsletter .done').removeClass('hide');
}
});
}
As you can see I'm currently using type: 'post'
Will that go to the create function in my controller automatically?
This is a great article on the default Rails routes: Rails Routing from the Outside In.
The routes will be the same regardless of whether you're using ajax or synchronous calls.

Resources