Rails 3 - link/button to run ajax request without redirecting - ajax

What's the best way for a link to run an ajax command (I'm using jquery in Rails 3.1)? So far I am trying to use a link to run code via the controller action "update_me."
views/products/new.html.erb has the following line:
<%= link_to "Update", :action => 'update_me' %>
In my products controller, I have:
def update_me
logger.debug 'ajax code will be here'
end
But this gives a missing template error:
Template is missing
Missing template products/update_me, application/update_me with {:handlers=>[:erb, :builder, :coffee], :formats=>[:html], :locale=>[:en, :en]}. Searched in: * "/home/ubuntu/code/preevio/app/views" * "/home/ubuntu/.rvm/gems/ruby-1.9.2-p290#rails31/gems/devise-1.4.3/app/views"
Why do I need to have a update_me.html.erb in my views? I assume that's what they want. Can't I just launch the code in the controller action/method without having to have a view for it? Or am I approaching this the wrong way?

I know this answer is a bit late, but I post it for anyone else who may get here trying to do something similar.
If you change your line of html to
<%= link_to "Update", :action => 'update_me', :remote => true %>
That should have the link to the provided action and do the ajax call for you.
You can look at the provided link to see the docs.
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Since Rails has convention over configuration, Rails expects an appropriate view for the action in the controller.
If you want to render nothing:
http://guides.rubyonrails.org/layouts_and_rendering.html#using-render
render :nothing => true

Related

Is there a good rails gem to output the view equivalent of rake routes?

What I'm looking for is a gem that could output a complete webpage version of each view a rails app has.
I realize I might not have correctly worded this. What I mean is I would like to see each route that has html output, but what the view actually looks like, not just a line saying what the view is.
In development (rails 4.x) you can simply go to any non-existent page and it will return all of the routes.
Example Screenshot: https://dl.dropboxusercontent.com/u/23115266/Screen%20Shot%202014-02-27%20at%209.21.03%20AM.png
The sextant gem allows you to see all your application's views in development by navigating to the /rails/routes URL.
https://github.com/schneems/sextant
Please correct me if I'm wrong, but it looks like you want a listing of view templates. Not sure there is a gem that can do this, but you could easily do it yourself with the following:
module ShowViewsHelper
def all_views_from_path(path)
helpers = Array(path).flat_map do |_path|
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_.erb$/
names = Dir["#{_path}/**/*.erb"].map { |file| file.sub(extract, '\1') }
names.sort!
end
helpers.uniq!
helpers
end
end
create a template somewhere with the following:
<ul>
<% all_views_from_path("app/views").each do |v| %>
<li><%= v %></li>
<% end %>
</ul>

Rails, Twitter Bootstrap, Simple Form, Heroku - Odd error when using ":wrapper => :prepend do" to get an add-on span

I have the following code in a form partial:
<%= f.association :client %>
<%= f.input :url, :wrapper => :prepend do %>
<%= content_tag :span, "http://www.", :class => "add-on" %>
<%= f.input_field :url, :class => 'span4' %>
<% end %>
Trying to load anything to do with this form partial e.g. new/edit etc causes Heroku to error. It works flawlessly on localhost.
The only obvious error in the Heroku logs is:
ActionView::Template::Error (undefined method `source' for nil:NilClass):
I'm afraid I don't really understand that but thought it might help anyone trying to answer this.
If I change the form partial code it works on Heroku no problem at all e.g.
<%= f.input :url, :input_html => {:class => 'span4' } %>
Obviously I lose my nice bootstrap add-on span so I'd rather find out what the issue is rather than running around it.
Shot in the dark, but maybe an initializer that sets up the prepend wrapper (like initializers/simple_form.rb or initializers/simple_form_bootstrap.rb) is not being run by Heroku, either because it's not checked into git, or because of some environment-specific logic in the initializers or environment files.
Well after testing and some help from Dan I finally got to the bottom of it. Unfortunately, it seems to be quite localised to my situation though.
But just in case anyone stumbles across this, the error I had was the following:
ActionView::Template::Error (undefined method `source' for nil:NilClass):
That was in the log and was THE SAME when I followed Dan's advise to turn on error reporting on the production site (set consider_all_requests_local = true in config/environments/production.rb).
I thought that the error was being caused in the template, however, it was some validation rules in the model. The validation rules for me where some regex to stop the user starting the input with a certain string. They worked perfectly fine on my local, but Heroku really wasn't liking it!
I removed those validation rules and voila, my nice bootstrap add-on span was working perfectly.

Remote Method Understanding?

In rails 3
While using remote method form submit, it affects the database twice with the same form values.
controller file:
#user_message = UserMessage.new(params[:user_message])
if #user_message.save
render :update
else
render :nothing => true
end
view file:
<%= form_tag ('/feedback/user_message'), :method =>'post', :remote=> true, :id=>'user_message' do%>
<%= hidden_field_tag 'user_message[user_id]', #user.user_id %>
<h2><%= #question %></h2>
<%= text_area_tag 'user_message[msg]',"", :size=>"40x5" %>
<%= submit_tag "Submit"%>
<% end %>
When I hit the submit button it creates two records on the table.
Why?
There may be couple of things that might be causing this
may be the ujs file is included twice may may be like
//= require jquery_ujs // expected to load from the rails-jquery gem
//= require_tree . // if any file is present in assets directory hierarchy it will be loaded
Or just a bug taking your sleep away
https://github.com/rails/jquery-ujs/issues/208
check out more solutions
Jquery Rails 3... form submits twice... deletes twice... help
Rails 3.1 remote requests submitting twice
This may also be related to the understanding of asset pipeline when and how use pecompiled assets.
I always use this config in development mode
config.server_static_assets = false
this forces the app to call the assets from app assets
and use precompiled assets from public in production mode
The problem most likely related to asset pipeline
You should precompiled the asset pipeline before.
This will create two copy of rails.js, one in your assets and one in application.js
This is a bug or gotcha in rails 3
See here http://www.ruby.code-experiments.com/blog/2011/10/another-gotcha-with-the-rails-31-asset-pipeline-or-why-are-my-jquery-ujs-ajax-requests-triggered-twi.html
Hope this help

Ruby - rails - how to create automatic hyperlinks for urls in the text/string rendered on the view?

How to create automatic hyperlinks for urls in the text/string rendered on the view?
I have a page that renders user activity log and in that log/text/string there are some random urls which I want to automatically hyperlink to open in a new browser window. There is this auto_link in ruby rails, how do I use that?
text = "User xyz accessed url - http://www.something.com on 04/13/2012 00:13:18GMT"
<%= "#{Text}" %>
I want this rendered with a hyperlink to the url. The URL could be anything anywhere in the text.
Use auto_link like this:
<%= auto_link(text) %>
If you want the generated links to open new browser windows (or tabs) add the option like so:
<%= auto_link(text, :html => { :target => '_blank' }) %>
As mentioned by pjumble in the comments, auto_link is no longer a part of Rails core as of Rails 3.1, this gem brings it back: https://github.com/tenderlove/rails_autolink Thanks pjumble!
For faster parsing, try https://github.com/vmg/rinku
require 'rinku'
Rinku.auto_link(text, mode=:all, link_attr=nil, skip_tags=nil)
Also one often need more filters than just linking, for example Youtube embedded videos. For this use: https://github.com/dejan/auto_html

Not able to render partial using facebox with rails

I am using facebox to get some information in a popup window.
I have got facebox.js and facebox.css file in my assets folder. I have included this code in my application.js file
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox()
});
I have link_to which looks like this <%=link_to "Create",new_activities_path, :rel => "facebox" %>
When I click on the create link I get a popup which is empty and does not render the form which is in the partial.
I am able to render this partial without facebox. I have been looking all over the net but it seems the documentation of facebox is not that good.
Can anyone guide me?
Thanks,
Was able to do it by tweaking the code little bit :-
now my link_to looks like this <%=link_to "Create",new_activity_path, :remote => true %>
I also have a new action in the controller and a corresponding new.js.erb file which has got the below mentioned code:-
$.facebox('<%= escape_javascript(render :partial => 'new') %>')
the code in the application.js remains the same. I am able to render the partial in _new.html.erb in a nice popup.
Hope it will be useful to others as the documentation of facebox is very poor.
Thanks,

Resources