I have a form on my website with a page where I can edit / remove / add mailboxes:
http://example.com/settings/mailboxes
http://example.com/settings/mailboxes/3/edit
http://example.com/settings/mailboxes/3
etc.
Whenever I do something to the mailbox (update, destroy) I'm getting this error:
Redirected to http://example.com/
Completed 406 Not Acceptable in 64ms
But the data gets updated.
Here's the controller code:
# PUT /mailboxes/1
def update
#mailbox = Mailbox.find(params[:id])
if #mailbox.update_attributes(params[:mailbox])
redirect_to(root_path, :notice => 'Mailbox was successfully updated.')
else
render :action => "edit"
end
end
# DELETE /mailboxes/1
def destroy
#mailbox = Mailbox.find(params[:id])
#mailbox.destroy
redirect_to(root_path)
end
Here's routes.rb info:
match 'settings.js' => 'settings#javascript', :via => :get, :format => :js
scope '/settings' do
# Directs /settings/mailboxes/* to Settings::MailboxesController
# (app/controllers/settings/mailboxes_controller.rb)
resources :mailboxes
end
What am I doing wrong? Here's what log shows:
if #mailbox.update_attributes(params[:mailbox])
(rdb:2) response.status
200
(rdb:2) next
/Users/Fallen/Projects/support-app/trunk/app/controllers/mailboxes_controller.rb:65
redirect_to(mailboxes_path, :notice => 'Mailbox was successfully updated.')
(rdb:2) response.status
200
(rdb:2) next
/usr/local/rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_controller/metal/implicit_render.rb:5
default_render unless response_body
(rdb:2) response_body
[" "]
(rdb:2) response.status
406
(rdb:2) cont
Started PUT "/settings/mailboxes/5" for 127.0.0.1 at 2011-10-14 12:54:38 +0200
Status Load (0.4ms) SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`name` = 'Incoming emails fetching' LIMIT 1
(0.1ms) BEGIN
(0.4ms) UPDATE `statuses` SET `last_action_at` = '2011-10-14 10:54:38' WHERE `statuses`.`id` = 1
(39.6ms) COMMIT
Processing by MailboxesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"0cip2dsYre9anfy/8rEgtuYcgrgC3si6aSuppjzxuHU=", "mailbox"=>{"name"=>"Dev Support #4", "sender_name"=>"example.com Support #4", "email_address"=>"support_dev4#example.com", "color"=>"B2EB3D"}, "commit"=>"Update Mailbox", "id"=>"5"}
Mailbox Load (0.5ms) SELECT `mailboxes`.* FROM `mailboxes` WHERE `mailboxes`.`id` = 5 LIMIT 1
Status Load (0.5ms) SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`name` = 'Incoming emails fetching' LIMIT 1
(0.1ms) BEGIN
(0.3ms) UPDATE `statuses` SET `last_action_at` = '2011-10-14 10:54:47' WHERE `statuses`.`id` = 1
(0.4ms) COMMIT
(0.2ms) BEGIN
(0.6ms) UPDATE `mailboxes` SET `color` = 'B2EB3D', `updated_at` = '2011-10-14 10:54:48' WHERE `mailboxes`.`id` = 5
Mailbox Load (0.7ms) SELECT `mailboxes`.* FROM `mailboxes`
(1.2ms) COMMIT
Mailbox Load (0.4ms) SELECT id, name, open_tickets_count FROM `mailboxes`
(0.3ms) SELECT COUNT(*) FROM `tickets` WHERE `tickets`.`closed` = 0
CACHE (0.0ms) SELECT COUNT(*) FROM `tickets` WHERE `tickets`.`closed` = 0
Redirected to http://localhost:3000/settings/mailboxes
Completed 406 Not Acceptable in 29008ms
406 happens when the content type that you are requesting is not one that an action knows how to respond with. For example if an action responds to html and json, but you request js, then it won't know how to respond.
If I'm not mistaken, it will do the work, but when it comes time to respond it will send back a 406.
I don't see any formats specified in your controller, but maybe you have them specified at the top with respond_to, or maybe I'm forgetting something about default behavior.
It looks like you are requesting js -- as an experiment, try wrapping this around your entire action:
respond_to do |format|
format.js do
# all your action code goes here...
end
end
Test adding the defaults format: :json in your routes.rb
# config/routes.rb
defaults format: :json do
# Your json routes here
# resources :example ...
end
Also, if you are using the responders gem, ensure that in your application_controller.rb you have a respond_to :json at the top.
I had this error and ended up here after googling. In my case I was missing the template but did not receive the usual Missing Template Error. I believe it was because I had respond_to :html at the top of the controller.
Related
IMPORTANT NOTE: The id does not matter, it is same in all cases.
I am only seeing the name field, not description, hours, etc even though these aren't null.
I have declared all standard routes through resources (with default format json), not individually.
I have even tried creating a projects/show.json.jbuilder file:
json.name #project.name
json.description #project.description
json.hours #project.hours
json.ownername #project.ownername
My projects/show method:
#project = Project.find(params[:id])
render :json => #project
FIRST EDIT:
I added logger.debug right before defining #project in my show method.
Now in my command prompt window for the local server, I am seeing:
Started GET "/projects/12" for 127.0.0.1 at 2015-02-25 16:36:45 -0500
ActiveRecord::SchemaMigration Load (0.2ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ProjectsController#show as HTML
Parameters: {"id"=>"12"}
Project Load (0.1ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1 [["id", 12]]
#<Project:0x007f95477e72f8>
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 51]]
Completed 200 OK in 42ms (Views: 15.2ms | ActiveRecord: 0.9ms)
I am wondering why I am seeing the "User Load" part, since my Project model does not belong to a User object or have any relationship with it (though in the past it may have had before that relationship was removed). Also, I don't think I saw
#<Project:0x007f95477e72f8>
earlier.
I solved my problem this way.
Basically, projects/12.json currently works and not projects/12. Since I am more interested in obtaining the data client side, it is ok for me. I would need a projects/show.html.erb page that calls all the project data through view helper methods, for the HTML to work.
def show
#project = Project.find(params[:id])
respond_to do |format|
format.html
format.json
end
end
projects/12.json works because I have a projects/show.json.jbuilder file (as I shared in my original question post):
json.name #project.name
json.description #project.description
json.hours #project.hours
json.ownername #project.ownername
I have been facing some problems with mailboxer gem . The reply and trash specifically , the messages are replied to and when selected to delete are sent to trash too but i haven't able to successfully redirect it to the inbox after it does so . I always keep getting the error "Cannot find user with id" Following is my controller code for the trash part -
def trash
conversation = Conversation.find(params[:id])
beta = current_userA || current_userB
case beta
when current_userA
conversation.move_to_trash(current_userA)
# redirect_to :conversations
when current_userB
conversation.move_to_trash(current_userB)
# redirect_to :conversations
end
respond_to do |format|
format.html { redirect_to conversation_path, notice: 'Conversation successfully trashed.' }
end
end
Logs
Started GET "/conversations/36" for 127.0.0.1 at 2014-08-28 10:19:56 +0530
Processing by ConversationsController#show as HTML
Parameters: {"id"=>"36"}
Message Load (0.5ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."type" IN ('Message') AND "notifications"."id" = $1 LIMIT 1 [["id", "36"]]
Conversation Load (0.4ms) SELECT "conversations".* FROM "conversations" WHERE "conversations"."id" = 34 LIMIT 1
Completed 404 Not Found in 4ms
ActiveRecord::RecordNotFound (Couldn't find userA without an ID):
app/controllers/conversations_controller.rb:160:in `show'
Rendered /usr/local/rvm/gems/ruby-1.9.3-p545/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.2ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p545/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p545/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (19.7ms)
Updated Log
After changing redirect_to conversation with redirect_to conversations
Started POST "/conversations/38/trash" for 127.0.0.1 at 2014-08-28 12:29:16 +0530
Processing by ConversationsController#trash as HTML
Parameters: {"authenticity_token"=>"CuXzMKNmD87qvfOuer4uhyTdysFS/5NxtfMZU3/Y5j0=", "id"=>"38"}
Conversation Load (0.4ms) SELECT "conversations".* FROM "conversations" WHERE "conversations"."id" = $1 LIMIT 1 [["id", "38"]]
Filmmaker Load (0.7ms) SELECT "userA".* FROM "userA" WHERE "userA"."id" = 67 LIMIT 1
Receipt Load (0.8ms) SELECT "receipts".* FROM "receipts" INNER JOIN "notifications" ON "notifications"."id" = "receipts"."notification_id" AND "notifications"."type" IN ('Message') WHERE "notifications"."conversation_id" = 38 AND "receipts"."receiver_id" = 67 AND "receipts"."receiver_type" = 'userA'
SQL (11.3ms) UPDATE "receipts" SET "trashed" = 't' WHERE (id = 82 )
User Load (29.7ms) SELECT "users".* FROM "users"
Completed 500 Internal Server Error in 110ms
NameError (undefined local variable or method `conversations' for #<ConversationsController:0x10961634>):
app/controllers/conversations_controller.rb:101:in `block (2 levels) in trash'
app/controllers/conversations_controller.rb:100:in `trash'
Please do advice what i am doing wrong , i have been at it since a day and i haven't found any solution to it .Needless to say , userA and userB are both different devise users. Any suggestions on it is most welcome .
Try to use a path in redirect, which you can get from rake_routes. Maybe the example given below will work for you.
respond_to do |format|
format.html { redirect_to inbox_path, notice: 'Conversation successfully trashed.' }
end
I have an issue whereas I am trying to update a boolean field in the database with true or false based off of a checkbox.
I am using rails 3.2.2, using RVM I tried with 3.2.9 with the same result. This is in development, and I'm running postgresql as my database.
I am running in development so I am not using attr_accessible until I get to a later testing date. All similar questions I have seen on here seem to be related to forgetting to add the boolean field to attr_accessible, so letting everyone know up front that's not the issue.
From a functional standpoint this piece of the app is basically a list of events (or tasks) that the user can schedule. There is an index page that will pull a list of all the tasks they have for the day. The user can then click the checkbox next to the task and it will update the task as completed using the boolean field in question via an ajax call.
Here is the pertinent section of the index view:
=render :partial => "mktg/home/tasks"
And here is the partial _tasks.html.haml
#mktg_home_tasks
- #tasks = Mktg::Event.where('DATE(starts_at) = DATE(?)', Date.today).all
- if #tasks.empty?
You currently have no tasks...
- else
- #tasks.each do |t|
= form_for t, :index => t.id, :remote => true do |task|
= task.check_box :completed
- if task.object.completed == true
= link_to task.object.title,{}, :class => 'strike_through'
- else
= link_to task.object.title
The update method of the events controller is basically scaffolded:
def update
#event = Mktg::Event.find(params[:id])
respond_to do |format|
if #event.update_attributes(params[:event])
format.js
format.html { redirect_to #event, :notice => 'Event was successfully updated.' }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => #event.errors, :status => :unprocessable_entity }
end
end
end
Here is the update.js.coffee:
jQuery ->
$('#mktg_home_tasks').empty()
$('#mktg_home_past_due').empty()
$('#mktg_home_tasks').append("<%= escape_javascript(render 'mktg/home/tasks')%>")
I have the following asset running that fires off the form submittal via jquery for the checkbox:
EDIT: from first comment below my post had incorrect indentation below.
jQuery ->
$(":checkbox").live "change", ->
$(this).parents("form:first").submit()
When I run the app as is, no values get committed to the database. The console dump looks like this:
Started PUT "/mktg/events/133" for 127.0.0.1 at 2012-12-10 17:21:42 -0800
Processing by Mktg::EventsController#update as JS
Parameters: {"utf8"=>"✓", authenticity_token"=>"5ahLYhEjY2QEh6G0XOrathPXMSMaiDoCAgABpDbCZck=", "mktg_event"=>{"133"=>{"completed"=>"1"}}, "id"=>"133"}
Mktg::Event Load (0.3ms) SELECT "mktg_events".* FROM "mktg_events" WHERE "mktg_events"."id" = $1 ORDER BY starts_at ASC LIMIT 1 [["id", "133"]]
(0.2ms) BEGIN
(0.3ms) SELECT "mktg_leads".id FROM "mktg_leads" INNER JOIN "mktg_event_leads" ON "mktg_leads"."id" = "mktg_event_leads"."lead_id" WHERE "mktg_event_leads"."event_id" = 133
(0.2ms) COMMIT
Mktg::Event Load (0.5ms) SELECT "mktg_events".* FROM "mktg_events" WHERE (DATE(starts_at) = DATE('2012-12-10')) ORDER BY starts_at ASC
Rendered mktg/home/_tasks.html.haml (3.4ms)
Rendered mktg/events/update.js.coffee (4.9ms)
Completed 200 OK in 66ms (Views: 6.0ms | ActiveRecord: 4.8ms)
So I then tried adding the following before_save method to the Event model:
def set_completed_value
if self.completed == 0
self.completed = false
else
self.completed = true
end
end
With this added I am able to select the events as being completed and it works by updating the database field with true, here is the console output from that:
Started PUT "/mktg/events/133" for 127.0.0.1 at 2012-12-10 16:48:59 -0800
Processing by Mktg::EventsController#update as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5ahLYhEjY2QEh6G0XOrathPXMSMaiDoCAgABpDbCZck=", "mktg_event"=>{"133"=>{"completed"=>"1"}}, "id"=>"133"}
Mktg::Event Load (0.3ms) SELECT "mktg_events".* FROM "mktg_events" WHERE "mktg_events"."id" = $1 ORDER BY starts_at ASC LIMIT 1 [["id", "133"]]
(0.1ms) BEGIN
(0.4ms) SELECT "mktg_leads".id FROM "mktg_leads" INNER JOIN "mktg_event_leads" ON "mktg_leads"."id" = "mktg_event_leads"."lead_id" WHERE "mktg_event_leads"."event_id" = 133
(0.3ms) UPDATE "mktg_events" SET "completed" = 't', "updated_at" = '2012-12-11 00:48:59.877945' WHERE "mktg_events"."id" = 133
(0.5ms) COMMIT
Mktg::Event Load (0.3ms) SELECT "mktg_events".* FROM "mktg_events" WHERE (DATE(starts_at) = DATE('2012-12-10')) ORDER BY starts_at ASC
Rendered mktg/home/_tasks.html.haml (29.4ms)
Rendered mktg/events/update.js.coffee (31.0ms)
Completed 200 OK in 36ms (Views: 31.8ms | ActiveRecord: 1.8ms)
But when I deselect the checkbox to mark a completed event as not completed the database is not updated. Here is the console output:
Started PUT "/mktg/events/133" for 127.0.0.1 at 2012-12-10 16:49:14 -0800
Processing by Mktg::EventsController#update as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5ahLYhEjY2QEh6G0XOrathPXMSMaiDoCAgABpDbCZck=", "mktg_event"=>{"133"=>{"completed"=>"0"}}, "id"=>"133"}
Mktg::Event Load (0.2ms) SELECT "mktg_events".* FROM "mktg_events" WHERE "mktg_events"."id" = $1 ORDER BY starts_at ASC LIMIT 1 [["id", "133"]]
(0.2ms) BEGIN
(0.3ms) SELECT "mktg_leads".id FROM "mktg_leads" INNER JOIN "mktg_event_leads" ON "mktg_leads"."id" = "mktg_event_leads"."lead_id" WHERE "mktg_event_leads"."event_id" = 133
(0.1ms) COMMIT
Mktg::Event Load (0.4ms) SELECT "mktg_events".* FROM "mktg_events" WHERE (DATE(starts_at) = DATE('2012-12-10')) ORDER BY starts_at ASC
Rendered mktg/home/_tasks.html.haml (3.4ms)
Rendered mktg/events/update.js.coffee (4.8ms)
Completed 200 OK in 9ms (Views: 5.5ms | ActiveRecord: 1.2ms)
I've never had to add a before_save method like that to get a checkbox to update a boolean value in the database. So I must be doing something wrong. I know I'm close. If anyone has help or suggestions I would really appreciate it.
Thank you...
EDIT: Trying the answer given by John Naegle
I changed
= form_for t, :index => t.id, :remote => true do |task|
To
= form_for t, :index => t.id, :as => :event, :remote => true do |task|
And I get the following console output
Started PUT "/mktg/events/133" for 127.0.0.1 at 2012-12-11 09:48:14 -0800
Processing by Mktg::EventsController#update as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5ahLYhEjY2QEh6G0XOrathPXMSMaiDoCAgABpDbCZck=", "event"=>{"133"=>{"completed"=>"1"}}, "id"=>"133"}
Mktg::Event Load (0.2ms) SELECT "mktg_events".* FROM "mktg_events" WHERE "mktg_events"."id" = $1 ORDER BY starts_at ASC LIMIT 1 [["id", "133"]]
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Completed 500 Internal Server Error in 2ms
ActiveRecord::UnknownAttributeError (unknown attribute: 133):
app/controllers/mktg/events_controller.rb:89:in `block in update'
app/controllers/mktg/events_controller.rb:88:in `update'
The record ID I am trying to change is 133 (which is the 'unknown attribute' above).
Here is the Update method with line numbers
#85 def update
#86 #event = Mktg::Event.find(params[:id])
#87
#88 respond_to do |format|
#89 if #event.update_attributes(params[:event])
#90 format.js
#91 format.html { redirect_to #event, :notice => 'Event was successfully updated.' }
#92 format.json { head :no_content }
#93 else
#94 format.html { render :action => "edit" }
#95 format.json { render :json => #event.errors, :status => :unprocessable_entity }
#96 end
#97 end
#98 end
Anything else I should try, or do you see any error in my code. Thanks again.
EDIT: Using John Naegle's answer from below I now have this working
= form_for t, :index => t.id, :as => :event, :remote => true do |task|
The above was causing the following console output and subsequent error:
"event"=>{"133"=>{"completed"=>"1"}}, "id"=>"133"}
By getting rid of :index the record ID stopped being passed incorrectly. Once I changed to this:
= form_for t, :as => :event, :remote => true do |task|
Everything started working correctly. Thanks for the help! I don't know how I'd get "unstuck" sometimes if it wasn't for this site and everyone who helps. I love this place.
It looks to me like your controller does this:
#event.update_attributes(params[:event])
But your post parameters are:
"utf8"=>"",
"authenticity_token"=>"5ahLYhEjY2QEh6G0XOrathPXMSMaiDoCAgABpDbCZck=",
"mktg_event"=>{"133"=>{"completed"=>"0"}},
"id"=>"133"}
params[:event] is empty.
hoping someone here can point me in the right direction.
I have a controller Update def running "update_attributes". Currently it returns false, with no error message. I'm fairly new to Ruby, but not to coding, and this has had me stumped for a good few days! I am trying to get the User model and db updated with the values specified below.
def update
#get currently logged in user
#user = current_user
#update user params based on edit form...
if #user.update_attributes(params[:user])
redirect_to profile_path, :notice => "Successfully updated profile."
else
render :action => 'edit'
end
end
my edit def....
def edit
#user = current_user
end
The form sends the following to this update method:
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
utf8: ✓
_method: put
authenticity_token: 9T4ihVI0p8j7pZEFxof3Bfahi2a+o3BPmtXJDnfHT4o=
user: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
first_name: Amanda
last_name: Ross
is_owner: '1'
email: example#googlemail.com
commit: Update
action: update
controller: users
id: '20'
And params[:user] returns:
{"first_name"=>"Amanda", "last_name"=>"Ross", "is_owner"=>"1", "email"=>"example#googlemail.com"}
All these fields are in attr_accessible in the Model, and I can create a user without any problem.
here's development.log output (sorry it's a bit messy)....
Started PUT "/users/20" for 127.0.0.1 at 2012-04-17 10:39:29 +0100
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9T4ihVI0p8j7pZEFxof3Bfahi2a+o3BPmtXJDnfHT4o=", "user"=> {"first_name"=>"Amanda", "last_name"=>"Ross", "is_owner"=>"1", "email"=>"example#googlemail.com"}, "commit"=>"Update", "id"=>"20"}
[1m[36mUser Load (1.0ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = 20 LIMIT 1[0m
>>>>>>>>>>>>
{"first_name"=>"Amanda", "last_name"=>"Ross", "is_owner"=>"1", "email"=>"example#googlemail.com"}
[1m[35m (0.0ms)[0m begin transaction
[1m[36mUser Exists (0.0ms)[0m [1mSELECT 1 FROM "users" WHERE (LOWER("users"."email") = LOWER('example#googlemail.com') AND "users"."id" != 20) LIMIT 1[0m
[1m[35mUser Exists (0.0ms)[0m SELECT 1 FROM "users" WHERE ("users"."email" = 'example#googlemail.com' AND "users"."id" != 20) LIMIT 1
[1m[36m (0.0ms)[0m [1mrollback transaction[0m
Rendered users/_form.html.erb (7.0ms)
Rendered users/edit.html.erb within layouts/application (10.0ms)
Rendered layouts/_includes.html.erb (30.0ms)
Could anyone possibly help point out where I'm going wrong, please?
Thanks in advance!
Both #update_attributes and #save will first check if your model instance is #valid? before continuing on to write to the database. If your model instance is not #valid?, then these methods will return false. To see what's wrong with your model instance, take a look at your model's #errors.
Rails.logger.info(#user.errors.messages.inspect)
Or, embedded in your method,
def update
#user = current_user
if #user.update_attributes(params[:user])
redirect_to profile_path, :notice => "Successfully updated profile."
else
# print the errors to the development log
Rails.logger.info(#user.errors.messages.inspect)
render :action => 'edit'
end
end
You can also get better introspection when updating attributes by calling update_attributes! instead, which raises exceptions instead of just returning false.
I've tried looking at other answers for this but I can't seem to figure out why my redirect isn't working.
So I'm using Devise with Rails 3.1, and I'm making a shopping site. Visitors aren't allowed to add things to their cart unless they are signed in. This is what I'm having trouble with: if they aren't signed in, I want to redirect them to the Items index page. Here's what I have:
class ItemsController < ApplicationController
def add_to_cart
#item = Item.find(params[:id])
if current_user
#item.update_attributes(:cart_id => #current_cart.id)
redirect_to :back
else
redirect_to categories_path, notice: 'You must sign in to add an item to your cart.'
end
end
.
.
.
end
As of right now, when I click the link to add to cart, the method gets executed (I can see Rails loading and defining #item in the server log), and it reaches the 'else' statement, but no redirect happens.
I've already generated scaffolding for the index, new, etc. (all the RESTful actions). Also, I'm sure that I'm reaching the add_to_cart method because I've tried debugging with some puts statements. What's happening here?
EDIT:
Also, another weird thing which may be of use... The server seems to try to execute this method twice, and tries to 'get' categories twice:
Started GET "/items/3/add_to_cart" for 127.0.0.1 at 2012-01-12 16:53:11 -0800
Processing by ItemsController#add_to_cart as JS
Parameters: {"id"=>"3"}
Category Load (0.3ms) SELECT "categories".* FROM "categories"
Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT 1 [["id", "3"]]
Redirected to http://localhost:3000/categories
Completed 302 Found in 26ms
Started GET "/items/3/add_to_cart" for 127.0.0.1 at 2012-01-12 16:53:11 -0800
Processing by ItemsController#add_to_cart as JS
Parameters: {"id"=>"3"}
Category Load (0.2ms) SELECT "categories".* FROM "categories"
Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT 1 [["id", "3"]]
Redirected to http://localhost:3000/categories
Completed 302 Found in 25ms
Started GET "/categories" for 127.0.0.1 at 2012-01-12 16:53:12 -0800
Processing by CategoriesController#index as JS
Category Load (0.2ms) SELECT "categories".* FROM "categories"
CACHE (0.0ms) SELECT "categories".* FROM "categories"
Rendered categories/index.html.erb within layouts/application (0.0ms)
Completed 200 OK in 35ms (Views: 28.5ms | ActiveRecord: 4.2ms)
Started GET "/categories" for 127.0.0.1 at 2012-01-12 16:53:12 -0800
Processing by CategoriesController#index as JS
Category Load (0.2ms) SELECT "categories".* FROM "categories"
CACHE (0.0ms) SELECT "categories".* FROM "categories"
Rendered categories/index.html.erb within layouts/application (0.0ms)
Completed 200 OK in 37ms (Views: 30.6ms | ActiveRecord: 4.2ms)
EDIT 2 (as requested by Delba)
resources :items do
member do
get 'add_to_cart'
end
end
EDIT 3: changing the else statement to respond to javascript
respond_to do |format|
format.js { redirect_to items_path, notice: 'You must sign in to add an item to your cart.' }
end
For anyone who may need answers to this question, simply replace redirect_to statements with the following:
respond_to do |format|
format.js
end
Then, in your views under items, make a add_to_cart.js.erb page, consisting of javascript to make notices, or do whatever. Here's what I put in mine:
alert("Need to be signed in")
EDIT: Also, for the part where it executes twice: this is somewhat unrelated, but for some reason by default Rails includes duplicate Javascripts. Specifically, look at application.js: it says require jquery and require jquery_ujs. Disable one of these and you're home free.
To disable one of these javascripts:
Go to assets/application.js
Remove the comments (the // ) before require jquery, require tree .
This way, Rails doesn't assume the default and instead includes only jquery and whatever other javascripts you have in assets/javascripts