RoutingError when using jQuery UI tabs with ajax - ajax

I'm getting ActionController::RoutingError in Profiles#show when I click a link to render a layout as part of my implementation of jQuery UI tabs. Here's my link_to:
<%= link_to "Messages", :controller => 'profiles', :action => 'profile_messages', :remote => true %>
My ProfilesController:
def profile_messages
#messages = User.find(#profile.user_id).messages
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #messages }
end
end
My profile_messages erb layout:
<div id="tabs-2">
<% for message in #user.messages %>
<div class="message-1">
</div>
<% end %>
</div><!-- end messages -->
Routes.rb:
resources :messages do
get "messages/profile" => :profile_messages
resources :responses
end
What I want to happen is: when you click the link created by my link_to, the layout in profile_messages.html.erb shows and loads the messages in that specific layout. What's going on here?
UPDATE: Adding the new line in Routes.rb gives me a new route:
message_messages_profile GET /messages/:message_id/messages/profile(.:format) {:action=>"profile_messages", :controller=>"messages"}
So I tried this in my Profiles show.html.erb I put:
<li><%= link_to "Messages", message_messages_profile_path, :remote => true %></li>
This gives me a RoutingError in Profiles#show -- No route matches {:action=>"profile_messages", :controller=>"messages"}. Even when I add the following into my MessagesController:
def profile_messages
#message = #user.messages.find(params[:user_id])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #messages }
end
end

get "messages/profile" => "messages#profile_messages", :as => profile_messages
resource :messages do
resource :responses
end
You don't have a route for that controller action. Rails doesn't map ":controller/:action/:id" by default any more. You can also just enable that route if you want. You could be able to reference this via profile_messages_path.
It's assuming 'show' is actually an id for messages here I think. The default routes for a resource are listed here: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions. Make sure you list your routes first!

resource :messages do
collection do
get :profile_messages
end
end
in your view
<li><%= link_to "Messages", "/messages/profile_messages", :remote => true %></li>

Thanks to the combined efforts of folks here on SO I was able to get this to work. Check out these questions for more code:
Exclude application layout in Rails 3 div
Rails 3 jQuery UI Tabs issue loading with Ajax

Related

How to pass param from 1 controller to another

I want to pass param from the following link in the view of Client controller
and the hash is #client, I want to pass #client.user_id, if i put (:id => #client.user_id) I am not able the get :id in the other controller Estate where I want to pass this param. What should I do ? Is there a way to do it ?(Two controllers are Client and Estate, I want to pass param from Client view to the Estate controllers create method. There is no nesting of resources here!)
<%= link_to "New Property", new_estate_path(:key => #client.first.user_id) %>
create action
def create
# #estate = Estate.new(params[:estate])
if current_user.Company.nil?
#estate = current_user.estates.build(params[:estate])
else
serve = User.find(params[:key])
debugger
#estate = serve.estates.build(params[:estate])
##estate.user_id = user_id
debugger
end
respond_to do |format|
if #estate.save
if #estate.Mgmt.nil?
EstateMailer.company_confirmation(#estate).deliver
end
format.html { redirect_to #estate, notice: 'Estate was successfully created.' }
format.json { render json: #estate, status: :created, location: #estate }
else
format.html { render action: "new" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
The code you pasted here should work:
<%= link_to "New Property", new_estate_path(:id => #client.user_id) %>
I think the problem is, you are expecting the params in create method but where as it actually goes to new method.
If you are looking for the create method. You can do
<%= link_to "New Property", estates_path(:id => #client.user_id), :method => :post %>
But that is not the right approach to use for POST actions. The right solution would be to use button_to.
<%= button_to "New Property", estates_path(:id => #client.user_id), :method => :post %>
link_to defaults to GET and button_to defaults to POST, as those are their primary usages. You can override :method if you want them to perform other action than their default.
Simply do this
<%= link_to "New Property", new_estate_path(user_id: #client.user_id) %>
In your controller:
params[:user_id]
You problem is that the create action is a POST not a GET. The link_to will only allow GET actions.
I made class variable in the controller outside all the actions.
##key, and in the new action assigned ##key the user_id that was coming through the params, and this ##key in the create action. I don't know if its the right way to do it. But it worked like a charm !

Remote Form Renders as HTML instead of JS

I have a simple form:
<%= form_for [current_user, #bookcase], :id => "shelf_update_form", :remote => true, :html => { :multipart => true} do |f| %>
<input id="bookcase_image" class="file" type="file" name="bookcase[image]" size="13">
<% end %>
That automatically uploads when a file has been selected:
$("#shelf_update_form").change(function() {
$("#shelf_update_form").submit();
});
I want the update action to render js view, but by default it renders html instead. I try forcing it to render js like so:
respond_to do |format|
format.js
end
But then I get this error:
NetworkError: 406 Not Acceptable
Even then, my log reports:
Processing by BookcasesController#update as HTML
How can I get it to process as JS instead?
UPDATE:
The view:
triggerAjaxHistory("<%= #href %>", false);
I get the same results with a more generic view, too:
alert("I work now!")
In the controller, do
respond_to do |format|
format.js if request.xhr?
end
Is your view named as .js.erb?
Can you check using firebug in your browser what exactly you are getting as the response? Turn on net logging and look at the response.
Also do you have the following in your layout?
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
Can you put in logger.info whatever_message commands to make sure you the controller action executes and you go into the correct view?
What happens if you specify the js format specifically in the controller as
class UserController < ApplicationController
respond_to :js, :only => :update, :layout => 'false`
What happens if you specify the format in form_for as :format => :js
Is your form nested within another form?

Rails 3 Ajax not working

I'm new to rails and ajax so I'm experimenting by building a simple app. I created a simple to do app with User and Tasks (user has many tasks). Using Devise to handle the authentication. I set up the task CRUD and implemented best_in_place (in place editing gem) and got it to work. What I wanted to do next is add ajax create and delete following some example resources such as creating a 100% ajax CRUD. After setting up all the necessary code for the create and destroy in tasks_controller, I'm getting DELETE http://localhost:3000/tasks/26 500 (Internal Server Error) as seen in the firebug console log. These are the errors printed in the console in firebug:
DELETE http://localhost:3000/tasks/26 500 (Internal Server Error)
jQuery.ajaxTransport.send
jQuery.extend.ajax
$.rails.rails.ajax
$.rails.rails.handleRemote
(anonymous function)
jQuery.event.dispatch
jQuery.event.add.elemData.handle.eventHandle
when the destroy link is clicked and same with create. The task got deleted and created after refresh but the ajax is just not working. I spent some time trying to figure out what's wrong but don't have any luck yet so I'm hoping I can get some help here while I keep digging into it. Below are my setups:
First the controller code:
def destroy
#task = current_user.tasks.find(params[:id])
#task.destroy
flash[:notice] = "Successfully destroyed post."
respond_to do |format|
format.html { }
format.js { }
end
end
def create
#task = current_user.tasks.build(params[:task])
respond_with(#task) do |format|
if #task.save
flash[:notice] = "Task was created successfully!"
respond_to do |format|
format.html { redirect_to tasks_url }
format.xml { render :xml => #task }
format.json { render :json => #task}
format.js
end
else
format.html { render :action => :new }
format.js
end
end
end
The task list partial to display the task list and delete
<table>
<% #tasks.each do |task| %>
<tr>
<td><%= best_in_place task, :detail %></td>
<!-- <p><%= best_in_place task, :completed, type: :checkbox %></p> -->
<td><%= link_to "Destroy", task, :confirm => 'Are you sure?', :method => :delete, :remote => true, :id=>'delete' %></td>
</tr>
<% end %>
</table>
The create form (without the other view stuff):
true) do |f| %>
<%= f.label :detail %>
<%= f.text_field :detail %>
<%= f.submit %> <% end %>
This is the javascript tag for application.html.erb (include jquery.js, jquery.ujs, application.js and other not so related js files):
Lastly I'm just trying to call an alert inside destroy.js.erb and with create.js.erb:
alert("Task was deleted");
Again, the crud is working normally when refreshed, it feels like the destroy.js.erb and create.js.erb is not linked somehow. I appreciated if you can provide a few hints.
Here is the error from the console after hitting delete:
ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each):
1:
2: <table>
3: <% #tasks.each do |task| %>
4:
5: <tr>
6: <td><%= best_in_place task, :detail %></td>
app/views/tasks/_tasks.html.erb:3:in `_app_views_tasks__tasks_html_erb___1747031968745406293_70257861453000'
app/views/tasks/destroy.js.erb:4:in `_app_views_tasks_destroy_js_erb___3673072470672404292_70257861472560'
It looks as though you have a syntax error in the destroy action. I think you're missing an end for the respond_to block.

Rails 3 -rendering partials and error "undefined local variable or method"

I have a photos in gallery (PhotosController) and I wanna add to every photo a comments. Into the statement of photos I added a partial for rendering comments + form for adding new comment.
My problem is, that when I send the form with a new comment, so I'll get the rendering error:
**NameError (undefined local variable or method `photo' for #<CommentsController:0x00000100ce0ad0>)**:
This is how looks my code:
views/photos/index.html.erb
<%= render #photos %>
views/photos/_photo.html.erb
<div><%=image_tag photo.photo.url(:thumb)%></div>
<div class="comments_to_photo">
<%= render :partial => 'photos/photo_comments', :locals => { :photo => photo }%>
</div>
photos/photo_comments
<%photo.comments.each do |cmnt|%>
<div><%=cmnt.comment%></div>
<%end%>
<%=form_tag comment_path, :remote => true do %>
<div><%=text_area_tag 'comment[comment]'%></div>
<%=submit_tag%>
<%end%>
controllers/CommentsController
def create
#comment = Comment.new(params[:comment])
respond_to do |format|
if #comment.save
format.html { redirect_to #comment, notice: 'Comment was successfully created.' }
format.js {
render :partial => '/photos/photo_comments', :locals => { :photo => photo } do |page|; page << "$(this).html('abcde');" end
}
else
format.html { render action: "new" }
format.js
end
end
end
I would like to refresh the form and comments statement in the photo, where was added a comment. Could anyone help me, please, how to avoid the error above?
Thank you in advance
EDIT: I added for refresh comments through AJAX the file _photo_comments.js.erb:
$('#photo_comment').html("<%= escape_javascript(render('photos/photo_comments')) %>");
And I get the error
ActionView::Template::Error (stack level too deep):
activesupport (3.2.1) lib/active_support/notifications/instrumenter.rb:23
with tens of this line:
Rendered photos/_photo_comments.js.erb (562.2ms)
and the last one
Completed 500 Internal Server Error in 580ms
What's wrong with rendering? I can't render partial html file from partial JS file?
In your controller you have:
:locals => { :photo => photo }
but the variable photo doesn't exist there. It should be:
:locals => { :photo => #comment.photo }
image_tag photo.photo.url(:thumb) <- Is it what you want to have photo.photo ?

Problem using link_to with remote option in rails 3

I'm working on rails 3 with link_to remote option.
This is my code structure.
View/punch/report.html.erb :
<%= link_to 'Punch report', punchreport_punch_index_path, :remote => true%>
<div id="punchform"> </div>
View/punch/punchreport.js.erb :
$("#punchform").html("<%= escape_javascript(render(:partial => "reportform"))%>");
and created a form inside
View/punch/_reportform.html.erb
and controller :
controller/punch_controller.rb
def report
end
def punchreport
respond_to do |format|
format.html { render report_punch_index_path }
format.js
end
end
note : punchreport_punch_index_path : /punch/punchreport
report_punch_index_path : /punch/report
I don get the ajax request working. instead of that, it redirects the page.
Any help
Thanks in advance
Sounds like your :remote => true is not being handled by an unobstrusive javascript event handler...
Do you have something called jquery-rails in your project? it should set a handler on "data-remote" attribute. Can you find it and post back what you have there?

Resources