Delete link doesn't work but button does - ruby-on-rails-3

I have a problem very similar to this one: rails 3 - link_to to destroy not working
But delete/destroy links do not work; I simply get redirected to the show page of the object. When I make a button for delete, it all works fine. But I'd like to understand why. Does anyone know?
I seems to be related to some .js files I am using/calling.
<!-- This link doesn't work -->
<%= link_to('Delete', post, :confirm => 'Are you sure?', :method => :delete) %>-->
<!-- This button does work -->
<%= button_to "delete", post, :method=>:delete, :class=>:destroy, :confirm => 'Are you sure?' %>
Post Controller
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to(posts_url) }
format.xml { head :ok }
end
end
UPDATE
After doing some further research it seem that everyone else having a similiar issue has included the following jquery library:
<script type="text/javascript" src="/javascripts/dragdrop.js"></script>
But I still don't know what the issue is...
LOG
Started GET "/posts/7" for 127.0.0.1 at Tue Jul 12 08:34:06 -0400 2011
Processing by PostsController#show as HTML
Parameters: {"id"=>"7"}
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 7 LIMIT 1
SQL (0.2ms) SELECT COUNT(*) FROM "comments" WHERE ("comments".post_id = 7)
Rendered posts/show.html.erb within layouts/application (116.5ms)
HTML generated
Delete
UPDATE: I've found that removing <script type="text/javascript" src="/javascripts/jquery-1.5.1.min.js"></script> fixes my problem. But I don't understand why. Is there a known conflict between jquery1.5.1 and rails 3.0.7?

Make sure you include these in your application layout:
<%= javascript_include_tag(:defaults) %>
<%= csrf_meta_tag %>

In my case adding
<%= javascript_include_tag(:defaults) %>
did not work. However explicitly defining java script files did the trick
<%= javascript_include_tag 'prototype' %>
<%= javascript_include_tag 'application' %>
Not sure yet why :defaults tag didn't work...

Rails will automatically load jquery for you if you have jquery-rails gem loaded via your Gemfile (this is the default rails configuration). It is then loaded via:
<%= javascript_include_tag(:defaults) %>
Have a look at app/assets/javascripts/application.js for the code that tells rails to add jquery via assets:
//= require jquery
//= require jquery_ujs
By trying to load another copy of jquery via this line:
<script type="text/javascript" src="/javascripts/jquery-1.5.1.min.js"></script>
You have caused a clash of jquery instances, the effect of which will be that neither will work.

Related

Using Parsley With Rails

I am trying to add parsley.js to a rails project to do client side form validation and can't seem to get it working.
I am using the gem for parsley for the rails asset pipline - https://github.com/mekishizufu/parsley-rails
gem "parsley-rails"
I went ahead and required it in my application.js file
//= require jquery
//= require parsley
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .
And then I added the following to the form I wish to validate on
<%= form_for :user, :html => {:"data-validate" => 'parsley'} do |user| %>
Which generates a data attribute in the html for the form
data-validate="parsley"
Then to check for the presence of the address I have:
<%= label_tag :current_address %>
<%= text_field_tag :address, nil, :data => {:"required" => 'true'} %>
Which renders a text field with a attribute for the text field
data-required="true"
Yet when I click submit no validation occurs and a post request is made. What else do I need to do in order to get parsley working on a rails 3 form? Much appreciated!
The gem uses Parsley-js version 1.2.3, as 2.0.0 is still a release candidate. Here are the docs for that version: http://parsleyjs.github.io/Parsley-1.x/documentation.html
The attributes are a bit different - the form_for tag should look like this:
<%= form_for :user, :html => {'parsley-validate' => ''} do |user| %>
and the text field:
<%= text_field_tag :address, 'parsley-required' => '' %>
Hope this helps.
Update
The 'parsley-rails' gem is now using v2.0.
The current version is now 2.0.5 and the docs can be found here http://parsleyjs.org
Using the rails gem you need to now add data-parsley-validate to the form and directives like required to the inputs.
Inside a rails form I had luck with:
<%= form_for #post, :html => {"data-parsley-validate" => true} do |f| %>
<%= f.text_field :title, :placeholder => "Title", :required => true %>
Hope this helps someone until parsley-rails gets some better links or basic usage docs in the readme. Might be a nice PR...
I got parsley to work in our Rails application by initializing parsley with
$('#form-id').parsley({ 'data-parsley-focus': 'first' });
the 'data-parsley-focus' is an option for where parsley will send the cursor if validations fail.
I included the gem as you did in gemfile, but my application.js loads parsley after the ujs adapter
//= require jquery
//= require jquery_ujs
//= require parsley

Rails 3 Search Action Redirects To Show?

I've ran into a weird problem in Rails. When I try and submit a search query with the following form on my Uploads controller:
<%= form_tag ({:controller => "uploads", :action => 'find_uploads'}), :method => "get" do %>
<%=h text_field_tag :search, params[:search], :id => 'search_field' %>
<br />
<%= submit_tag "Search", :style=>"display:inline;" %>
<% end %>
I get redirected to the following url and error page:
/uploads/find_uploads?utf8=✓&search=bot&commit=Search
ActiveRecord::RecordNotFound in UploadsController#show
Couldn't find Upload with id=0
My find_uploads route: get 'uploads/find_uploads' => "uploads#find_uploads"
And when I did I rake routes this is what I got:
uploads_find_uploads GET /uploads/find_uploads(.:format) {:controller=>"uploads", :action=>"find_uploads"}
Everything seems to be in order... not sure why it's not working out as expected. For debugging purposes I dropped breakpoints in both my find_uploads and show actions and neither of them were reached so this error message must be lying to me as the UploadsController show action is never called!
This form is being rendered on my index page if it counts for anything.
I think it's taking find_uploads for an id.
Declare your routes like that:
resources :uploads do
collection do
get :find_uploads
end
end
ps: currently, when you do rake routes, /uploads/find_uploads is after /uploads/:id right?

Rails 3 Delete Confirmation not Displaying

I have the following in a namespace enviroment.
This is in my Article Index File to delete an Article.
<%=button_to "Delete", admin_article_path(article), :class => 'button', :confirm => "Are you sure?", :method => :delete%>
However it deletes the record but the confirmation does not come up.
Any ideas why? or have i got this wrong?
Thanks in Advance
Make sure your included javascripts include rails.js (usually, this means making sure rails.js is in app/assets/javascripts, since <%= javascript_include_tag "application" %> will likely include the entire tree).
Also, make sure that the <head> tag of your layout contains <%= csrf_meta_tag %>.

Rendered partial not receiving params

I'm trying to implement an 'edit' link that brings up a form to change a displayed attribute on a page.
My layout has:
<div id="company_info">
<%= yield :company_info %>
</div>
<div id="edit_company_info">
</div>
My view has:
<%= content_for :company_info do %>
<%= render 'company_info' %>
<%= link_to "Edit", 'company_info_form', :class => 'btn btn-mini', :method => :get, :remote => true %>
My controller has:
def company_info_form
#company = Company.get(params[:id])
respond_to do |format|
format.js
end
end
My company_info_form.js.erb file has:
$('#edit_company_info').html("<%= escape_javascript(render "company_info_form") %>");
Upon clicking the link, my server shows:
Started GET "/companies/company_info_form" for 127.0.0.1 at 2012-03-12 20:19:13 -0700
Processing by CompaniesController#show as JS
Parameters: {"id"=>"company_info_form"}
Completed 500 Internal Server Error in 1ms
RuntimeError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):
app/controllers/companies_controller.rb:9:in `show'
So I think this is a routing issue-- but I have no idea how to fix it. How do I get the company_id param that is on my current page to be recognized by the partial I'm loading as well?
I'm on /companies/1, but the link is to companies/company_info_form, losing the "company_id = 1" param.
Yes, the issue is with your routes and with your link as you have pointed out.
The first issue can be ascertained as it says Processing by CompaniesController#show as JS. So, its actually going to companies#show where it tries to find a company based on id. But, since no correct id is passed, it errors out.
The second issue is because your link is to companies/company_info_form, as you pointed out, since you have used 'company_info_form' as the path in your link for edit. And you haven't passed current company to the link either.
Since you haven't posted your routes file, which you should have, since you have identified a potential problem with routes , I'll present my own.
In your routes :
resources :companies do
member do
get 'company_info_form'
end
end
That will provide you with
company_info_form_company GET /companies/:id/company_info_form(.:format) companies#company_info_form
Then you can provide the link as :
<%= link_to "Edit", company_info_form_company_path(#company) %>

Ajax Callbacks in Rails 3 with Prototype, not jQuery

I'm upgrading an app from Rails 2 to 3 and am reworking all of the remote functions to use Unobtrusive Javascript. Where I'm struggling is handling ajax callbacks in UJS.
There are a lot of resources I've found that show how to implement these callbacks with jQuery, but not much for prototype. Perhaps you can help me figure this out.
In Rails 2, I had this:
<% remote_form_for #foo, {:loading => "loading_function()", :complete => "complete_function()" } do |f| %>
...
<% end %>
In Rails 3, I have this:
<%= form_for #foo, :remote => true do |f| %>
....
<% end %>
From what I've figured out so far (which may be wrong), I need to attach my old loading/complete functions to the form so that they'll be fired by the handleRemote function in Rails.js. I'm just not sure how to go about that.
Again, I'm doing this in Prototype. So answers specific to that framework are appreciated.
The answer is the following:
<%= form_for #foo, :remote => true do |f| %>
...
<% end %>
...
<script type='text/javascript'>
$('edit_foo').observe('ajax:before', loading_function());
$('edit_foo').observe('ajax:complete complete_function());
</script>
Try this link. Yes, it is JQuery, but JQuery and Prototype do not differ the way how things work together. Here is a code fragment that adds a new task directly in the index page - and it uses Prototype:
views/tasks/_newform.html.erb:
<%= form_for(#task, :remote => true) do |f| %>
<div>
<%= f.label 'Add a new task: ' %>
<%= f.text_field :name %>
</div>
<div>
<%= f.submit %>
</div>
<% end %>
views/tasks/index.html.erb:
<div id='newform'>
<%= render :partial => "newform", :locals => { :#task => Task.new } %>
</div>
views/tasks/create.js.rjs:
page.insert_html :after, 'tablehead', :partial => #task
page.replace_html 'newform',:partial => "newform", :locals => { :#task => Task.new }
Edit: you need to add "format.js" to our create method of the task controller
For people with a similar issue, it may also help to look at the source code for the remote helpers in the Rails 2.3.x source code.
In my case, I wanted to figure out what to do with the ':update' parameter, as in:
remote_form_for(#obj, :update => "new_obj", :before => "some js code") do |f|
I had to find the update functionality in the remote_function code.
For my specific issue, it looks like it's impossible to get the equivalent of :update with Rails 3 UJS helpers. The rails.js in Rails 3 wraps :remote => true requests with the Ajax.Request(...), whereas the :update function in Rails 2 wraps Ajax requests with Ajax.Updater(...). For people looking to replace the :update feature from Rails 2, I see 2 options:
Switch to jquery-rails, so that you can access the response from the Ajax request, with code like this:
$("#elem").bind("ajax:complete", function(et, e){
$("#results").html(e.responseText);
});
Write your own Prototype based code to grab the form and submit it via ajax, using Ajax.Updater(...) instead of Ajax.Request. Do NOT use :remote => true, since this will attempt to use Ajax.Request.
Side note: I played around with the callback object provided in the ajax:complete event
$('new_obj').observe('ajax:complete', function(request){
console.info(request);
});
The request object doesn't appear to contain the response anywhere in it. It is pretty massive, though, so I could be wrong. Hopefully this will help someone else trying to upgrade from Rails 2 to 3, though.
There's a way to get the response from the Ajax.Request invocation, if you were using remote_form_for with :update option. So, you probably don't need to change it to use Ajax.Updater as a workaround. Basically, you use respone.memo.responseText, in your example it would be something like this:
$('new_obj').observe('ajax:complete', function(response){
console.info(response.memo.responseText);
// Probably you would use it like this:
$('new_obj').update(response.memo.responseText);
});