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
Related
I have three main Classes: Users, Vocabs and Tags. A User has many Tags. Tags has-and-belongs-to-many Vocabs (and the other way around).
How can I order a collection of Tags when getting them through a Vocab-Object?
#vocab.tag
gets the tags from the joins table, which has no created_at column.
Is there a handy way to solve this problem?
I am pretty new to Rails so excuse me if this is obvious.
EDIT: I just tried
#tags = #vocab.tags.order('tags.created_at DESC')
but without success.
The computer says:
Started GET "/users/1/vocabs/61" for 127.0.0.1 at 2014-12-11 15:41:15 +0100
Processing by VocabsController#show as HTML
Parameters: {"user_id"=>"1", "id"=>"61"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Vocab Load (0.3ms) SELECT "vocabs".* FROM "vocabs" WHERE "vocabs"."user_id" = ? AND "vocabs"."id"
= ? ORDER BY created_at DESC LIMIT 1 [["user_id", 1], ["id", 61]]
Tag Load (0.5ms) SELECT DISTINCT "tags".* FROM "tags" INNER JOIN "tags_vocabs" ON "tags"."id" =
"tags_vocabs"."tag_id" WHERE "tags_vocabs"."vocab_id" = ? [["vocab_id", 61]]
Rendered shared/_error_messages.html.erb (0.2ms)
Rendered vocabs/show.html.erb within layouts/application (10.7ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.html.erb (1.1ms)
Completed 200 OK in 602ms (Views: 587.3ms | ActiveRecord: 1.2ms)
The controller action looks like this:
def new_tag
#user = current_user
#vocab = #user.vocabs.find(params[:id])
#tags = #vocab.tags.order('tags.created_at DESC')
#tag = current_user.tags.build(name: params[:tag])
if #tag.save
#vocab.tags<<#tag
flash.now[:success] ='Tag successfully created.'
redirect_to user_vocab_path(#user, #vocab)
else
flash.now[:danger] = "Tag could not be created!"
render :action => "show"
end
end
My controller's update function looks like this:
def update
#cohort = Cohort.find(params[:cohort][:id])
#cohort.update_attributes(params[:cohort])
respond_to do |format|
format.js {render action: "show", layout: "courses"}
end
end
When I trigger the update function (via js), get the following in my Rails console:
Started PUT "/cohorts/41" for 127.0.0.1 at 2014-07-18 21:57:26 -0400
Processing by CohortsController#update as */*
Parameters: {"cohort"=>{"id"=>"41", "user_id"=>"17", "room_id"=>"16"}, "id"=>"41"}
Cohort Load (0.1ms) SELECT "cohorts".* FROM "cohorts" WHERE "cohorts"."id" = ? LIMIT 1 [["id", "41"]]
(0.0ms) begin transaction
(0.3ms) UPDATE "cohorts" SET "room_id" = 16, "updated_at" = '2014-07-18 21:57:26.303928' WHERE "cohorts"."id" = 41
(8.5ms) commit transaction
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17 LIMIT 1
Course Load (0.1ms) SELECT "courses".* FROM "courses" WHERE "courses"."id" = 21 LIMIT 1
Timeperiod Load (0.1ms) SELECT "timeperiods".* FROM "timeperiods" WHERE "timeperiods"."id" = 37 LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17 LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE (role = 'faculty' OR role = 'admin')
FacultyReport Load (0.1ms) SELECT "faculty_reports".* FROM "faculty_reports" WHERE "faculty_reports"."cohort_id" = 41 LIMIT 1
Room Load (0.1ms) SELECT "rooms".* FROM "rooms"
Room Load (0.1ms) SELECT "rooms".* FROM "rooms" WHERE "rooms"."id" = 16 LIMIT 1
Enrollment Load (0.1ms) SELECT "enrollments".* FROM "enrollments" WHERE "enrollments"."cohort_id" = 41
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17 LIMIT 1
Rendered cohorts/show.html.erb within layouts/courses (12.3ms)
Rendered layouts/_header.html.erb (2.1ms)
Rendered layouts/_leftnav.html.erb (0.8ms)
Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 44.7ms (Views: 31.1ms | ActiveRecord: 10.0ms)
Notice it says Rendered cohorts/show.html.erb within layouts/courses (12.3ms). In the browser itself, no refresh or re-rendering occurs. If I manually refresh the page, I can see the changes were made but the page itself change.
Also, if I change render to redirect_to I get (in the console) a redirect loop that goes for about 14 iterations and then stops and no changes in the browser.
respond_to
From your comments & looking at your code, you need to remember how Rails repond_to block works
When you call format.js, Rails will automatically look for [action_name].js.erb in your views/controller folder. This file will essentially run when you hit the update action from ajax / JS, it will perform the function & then look for update.js.erb to run.
You have several issues with your code:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def update
#cohort = Cohort.find(params[:cohort][:id])
#cohort.update_attributes(params[:cohort])
respond_to do |format|
format.js {render layout: "courses"} #-> automatically loads views/your_controller/update.js.erb
end
end
end
--
Update
Something else you should consider is your update functionality - specifically that you're trying to update a model with naked params (you should use strong_params):
def update
#cohort = Cohort.find params[:cohort][:id]
#cohort.update(cohort_params)
end
private
def cohort_params
params.require(:cohort).permit(:your, :params)
end
Edit:
I changed format.js {render action: "show", layout: "courses"} to format.js {render "update.js.erb"} and it works as intended.
I'm trying to use the split class to split up an array. I keep getting this error:
MethodError (undefined method `split' for nil:NilClass):
This is what I'm trying to do:
def create
#listing.landlord = current_landlord
if #listing.save
photo_id_array = params[:images].split(/,/)
photo_id_array.each do |image|
#image = Photo.find_by_id("photo.id")
#image.listing_id = #listing.id
end
render :show, :status => 200
else
render :status => 403, :json => {:errors => #listing.errors}
end
end
I'm running Rails 3.2.9. Any ideas into what may be causing this?
Edit:
Here is the full post:
Started POST "/listings" for 127.0.0.1 at 2012-12-12 01:04:52 -0800
Processing by ListingsController#create as application/json; charset=utf-8
Parameters: {"listing"=>{"street_address"=>"123 main st", "city"=>"los angeles", "state"=>"ca", "availability"=>"12 Dec 2012", "price"=>"2000", "period"=>"2", "category"=>"1", "cats"=>"false", "dogs"=>"false", "square_footage"=>"0", "bedrooms"=>"3", "bathrooms"=>"2", "short_description"=>"tree-lined street", "long_description"=>"big yard", "images"=>["70621", "70622", "70620"]}, "auth_token"=>"6489Cn7KeTmejSxaWsws"}
WARNING: Can't verify CSRF token authenticity
User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."authentication_token" = '6489Cn7KeTmejSxaWsws' LIMIT 1
Landlord Load (0.6ms) SELECT "landlords".* FROM "landlords" WHERE "landlords"."authentication_token" = '6489Cn7KeTmejSxaWsws' LIMIT 1
Role Load (0.5ms) SELECT "roles".* FROM "roles" WHERE "roles"."name" = 'admin' LIMIT 1
Role Exists (0.7ms) SELECT 1 AS one FROM "roles" INNER JOIN "landlords_roles" ON "roles"."id" = "landlords_roles"."role_id" WHERE "landlords_roles"."landlord_id" = 5867 AND "roles"."id" = 1 LIMIT 1
Completed 500 Internal Server Error in 275ms
NoMethodError (undefined method `split' for nil:NilClass):
app/controllers/listings_controller.rb:8:in `create'
Rendered /Users/rigelstpierre/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.9ms)
Rendered /Users/rigelstpierre/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.1ms)
Rendered /Users/rigelstpierre/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (16.9ms)
Use:
params[:listing][:images]
And it's already an Array, no need to split. You can directly do: params[:listing][:images].each.
params[:images] is nil, you're after params[:listing][:images] I assume.
Your params are structured like: "listing"=>{"images"=>["70621", "70622", "70620"]}.
Plus, you needn't split it, it's an array. Access each item of the array with: params[:listing][:images].each do |i|
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
This is my route:
scope ":username" do
resources :feedbacks
end
So when I go to mydomain.com/test/feedbacks/10 it shows the correct feedback with id=10 that belongs to username=test.
But, if I go to mydomain.com/test2/feedbacks/10 it shows me the same feedback with id=10, which does NOT belong to username=test2.
How do I restrict this from happening?
I am using the Vanity gem to give me the username in the URL, this is what that route looks like:
controller :vanities do
match ':vname' => :show, :via => :get, :constraints => {:vname => /[A-Za-z0-9\-\+\#]+/}
end
Edit 1:
That is to say, for clarity's sake, when I go to mydomain.com/test/feedbacks/10 and /test2/feedbacks/10, it shows me the same view for the same record (in which case, the latter version would be wrong because it should be telling me that no such record exists, but it's not. It is just displaying the correct record for test/feedbacks/10).
Edit 2:
Here are the logs of both requests:
The right request
Started GET "/test-3/feedbacks/7" for 127.0.0.1 at 2011-09-14 02:48:15 -0500
Processing by FeedbacksController#show as HTML
Parameters: {"username"=>"test-3", "id"=>"7"}
Feedback Load (0.5ms) SELECT "feedbacks".* FROM "feedbacks" WHERE "feedbacks"."id" = ? LIMIT 1 [["id", "7"]]
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
Rendered feedbacks/show.html.erb within layouts/application (36.2ms)
Completed 200 OK in 188ms (Views: 184.3ms | ActiveRecord: 1.8ms)
The wrong request
Started GET "/test2/feedbacks/7" for 127.0.0.1 at 2011-09-14 02:48:28 -0500
Processing by FeedbacksController#show as HTML
Parameters: {"username"=>"test2", "id"=>"7"}
Feedback Load (0.1ms) SELECT "feedbacks".* FROM "feedbacks" WHERE "feedbacks"."id" = ? LIMIT 1 [["id", "7"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
Rendered feedbacks/show.html.erb within layouts/application (37.6ms)
Completed 200 OK in 50ms (Views: 47.5ms | ActiveRecord: 1.2ms)
Your show action should look something like
def show
#user = User.find_by_username(params[:username])
if #user == current_user
...
render "show"
else
flash[:alert] = "Record doesn't exist"
redirect_to root_path
end
end
I took the liberty of adding in #Benoit's suggestion.