Element.update rjs error while using link_to_remote in rails - rjs

I am using rails 2.3.2
I have a link_to_remote functions
<%= link_to_remote "Comments ", {
:url => {:controller => "blogs",:action => "fetchcomments",:id => blog.id}} %> |
and the rails action as
def fetchcomments
unless params[:id].nil?
#blog = Blog.find(params[:id])
respond_to do |format|
format.js do
render :update do |page|
page.replace_html("comm", 'hi')
end
end
end
end
The above code throws me the error as
try {
Element.update("comm", "hi");
} catch (e) { alert('RJS error:\n\n' + e.toString());
alert('Element.update(\"comm\", \"hi\");'); throw e }
Please give me suggestions

Remove unless params[:id].nil? and it will work if you have an element with the id 'comm' on the page that makes the request. Of course it will replace whatever is inside with the word 'hi'.

Related

How to download search results of index page using axlsx?

First, I am really sorry if this question is too trivial. I am new with rails and couldn't figure out where i am doing it wrong.
I have a model named Costing and in it's index page i have a search form. I am trying to use 'axlsx' gem to download only the search results but I always get all the rows. I am also using 'will_paginate' gem.
Here is my code.
//costings_controller.rb
def index
#costings = Costing.search(params[:search] , params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #costings }
format.xlsx {
send_data #costings.to_xlsx.to_stream.read, :filename => 'costings.xlsx', :type => "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet"
}
end
end
// index.html.erb
<%= link_to 'Download Costings', url_for(:format=>"xlsx") %>
Please help me here.
Thanks a lot in advance.
Here is the code that I made for a demo of axlsx gem. Browse through it and implement your requirement in the controller. Here is the output of this demo.
//costings_controller.rb
def download
#costings = Costing.search(params[:search] , params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #costings }
format.xlsx {
send_data #costings.to_xlsx.to_stream.read, :filename => 'costings.xlsx', :type => "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet"
}
end
end
// index.html.erb
<%= form_for :costing, url: download_costing_index_path do %>
...
<% end %>
//routes
resources :costing do
collection do
post :download, :defaults => { :format => 'xlsx' }
end
end

Get current stack trace in Ruby without raising an exception

I want to log the current backtrace (stacktrace) in a Rails 3 app without an exception occurring. Any idea how?
Why do I want this? I'm trying to trace the calls that are made when Rails looks for a template so that I can choose a part of the process to override (because I want to change the view path for a particular subclassed controller of mine).
I'd like to call it from the file: gems\actionpack-3.2.3\lib\action_dispatch\middleware\templates\rescues\missing_template.erb. I know that's not best practice, but I know it's downstream of the stack from where the search for templates occurs.
You can use Kernel#caller:
# /tmp/caller.rb
def foo
puts caller # Kernel#caller returns an array of strings
end
def bar
foo
end
def baz
bar
end
baz
Output:
caller.rb:8:in `bar'
caller.rb:12:in `baz'
caller.rb:15:in `<main>'
Try using
Thread.current.backtrace
I use this to show a custom error page when exception are raised.
rescue_from Exception do |exception|
logger.error exception.class
logger.error exception.message
logger.error exception.backtrace.join "\n"
#exception = exception
# ExceptionNotifier::Notifier.exception_notification env, #exception
respond_to do |format|
if [AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, ActionController::RoutingError, ActionController::UnknownAction].include?(exception.class)
format.html { render :template => "errors/404", :status => 404 }
format.js { render :nothing => true, :status => 404 }
format.xml { render :nothing => true, :status => 404 }
elsif exception.class == CanCan::AccessDenied
format.html {
render :template => "errors/401", :status => 401 #, :layout => 'application'
}
# format.js { render :json => { :errors => [exception.message] }, :status => 401 }
# format.js { render :js => 'alert("Hello 401")' }
format.js { render :template => 'errors/401.js.erb' }
else
ExceptionNotifier::Notifier.exception_notification(env, exception).deliver
format.html { render :template => "errors/500", :status => 500 } #, :layout => 'im2/application' }
# format.js { render :nothing => true, :status => 500 }
format.js { render :template => 'errors/500.js.erb' }
end
end
end

Why does this rescue syntax work?

Ok so I have this method of an application I am working with and it works in production. My question why does this work? Is this new Ruby syntax?
def edit
load_elements(current_user) unless current_user.role?(:admin)
respond_to do |format|
format.json { render :json => #user }
format.xml { render :xml => #user }
format.html
end
rescue ActiveRecord::RecordNotFound
respond_to_not_found(:json, :xml, :html)
end
rescues do not need to be tied to an explicit begin when they're in a method, that's just the way the syntax is defined. For examples, see #19 here and this SO question, as well as the dupe above.
rescue can work alone . no need of begin and end always .
You can use rescue in its single line form to return a value when other things on the line go awry:
h = { :age => 10 }
h[:name].downcase # ERROR
h[:name].downcase rescue "No name"
rescue word is part of method definition
But in controllers better to rescue errors with rescue_from
try this
def edit
begin
load_elements(current_user) unless current_user.role?(:admin)
respond_to do |format|
format.json { render :json => #user }
format.xml { render :xml => #user }
format.html
end
rescue ActiveRecord::RecordNotFound
respond_to_not_found(:json, :xml, :html)
end
end

AbstractController::DoubleRenderError with my respond_to in rspec

I got this Rails3 action:
def export
respond_to do |format|
format.tdl { render :xml => #template.export_as_tdl and return }
format.json { render :json => #template.export_as_json }
end
end
and filter before the export:
def find_environment
#environment = KTEnvironment.find(params[:environment_id])
raise HttpErrors::NotFound, _("Couldn't find environment '#{params[:environment_id]}'") if #environment.nil?
#environment
end
and this rspec:
describe "export" do
it "should call export_as_json" do
#tpl.should_receive(:export_as_json)
get :export, :id => TEMPLATE_ID
end
it "should call export_as_tdl" do
#tpl.should_receive(:export_as_tdl)
get :export, :id => TEMPLATE_ID, :format => 'tdl'
end
end
I also defined the following MIME type:
Mime::Type.register "application/tdl-xml", :tdl
When I try to run my rspec tests, I am constantly getting:
1) Api::TemplatesController export should call export_as_tdl
Failure/Error: get :export, :id => TEMPLATE_ID, :format => 'tdl'
AbstractController::DoubleRenderError:
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
# ./app/controllers/api/api_controller.rb:135:in `render_exception'
# ./app/controllers/api/api_controller.rb:133:in `render_exception'
# ./app/controllers/api/api_controller.rb:22:in `__bind_1314974553_619675'
# ./spec/controllers/api/templates_controller_spec.rb:178
I have no clue what is happening there. This is my exception rendering code:
def render_wrapped_exception(status_code, ex)
logger.error "*** ERROR: #{ex.message} (#{status_code}) ***"
logger.error "REQUEST URL: #{request.fullpath}"
logger.error pp_exception(ex.original.nil? ? ex : ex.original)
orig_message = (ex.original.nil? && '') || ex.original.message
respond_to do |format|
format.json do
render :json => {
:errors => [ ex.message, orig_message ]
}, :status => status_code
end
format.all do
render :text => "#{ex.message} (#{orig_message})",
:status => status_code
end
end
end
Ah so the render_exception general method in my api_controller is called. It looks like:
def render_exception(status_code, exception)
logger.error pp_exception(exception)
respond_to do |format|
format.json { render :json => {:errors => [ exception.message ]}, :status => status_code }
format.all { render :text => exception.message, :status => status_code }
end
end
Try disabling your error handler, the root cause should come up on its own.

Rails 3: update method redirection problem

Trying to build a CMS for a blog using rails 3.
In my routes.rb...
namespace :admin do
resources :posts
root :to => "home#index"
end
In Admin::PostsController...
def update
#post = Post.find(params[:id])
respond_to do |format|
if #post.update_attributes(params[:post])
format.html { redirect_to(#post,
:notice => 'Post was successfully updated.')}
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #post.errors,
:status => :unprocessable_entity }
end
end
end
I had to change the first line of admin/_form.html.erb due to a previous 'undefined method' error that was driving me crazy. Was trying to point the browser to a nonexistent "post_path".
<%= form_for(#post, :url => admin_posts_path(#post)) do |f| %>
All other methods for posts are working as expected. Upon form submission (update) - the rails server...
Started POST "/admin/posts.1"
ActionController::RoutingError (No route matches "/admin/posts.1"):
First, curious as to why it is using POST instead of PUT for the update.
Second, I can't figure out why the URL is being interpreted as "/admin/posts.1" and how to fix it.
Has anyone else run into this problem? (and yes, I am following the rubyonrails.org guides closely to help me). Any help would be greatly appreciated.
EDIT:
Changed admin_posts_path(#post) to admin_post_path(#post) per theIV.
the rails server...
NoMethodError (undefined method 'post_url' for #<Admin::PostsController:0x00000102b26ff8>):
app/controllers/admin/posts_controller.rb:55:in 'block (2 levels) in update'
app/controllers/admin/posts_controller.rb:53:in 'update'
I believe you should be hitting admin_post_path(#post), not admin_posts_path(#post).
Look at the table that lists all of the helpers created for your routes on guides.rubyonrails.org.
EDIT: Also, have you tried the array style of urls? It's pretty convenient.
<%= form_for([:admin, #post]) do |f| %>
EDIT 2: My guess as to "undefined method post_url" is from your update action here:
format.html { redirect_to(#post,
:notice => 'Post was successfully updated.')}
It needs to be namespaced as well:
format.html { redirect_to([:admin, #post],
:notice => 'Post was successfully updated.')}

Resources