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|
Related
When I enter an incorrect track_id in url for example : tracks/123456
=> it returns 404 not found as expected !
If I try with incorrect challenge_id which is one of my other model : tracks/1/challenges/12345
=> it return null instead of 404 not found.
The code of both seems to be the same so I can't found the issue.
If you could help me to found why I get null instead of 404, seeing the code below :
routes.rb
resources :tracks do
resources :challenges do
resources :ressources
end
end
challenges_controller.rb
def show
render json: #challenge, include: [:ressources, :challenges_startups]
end
private
def set_challenge
#track = Track.find(params[:track_id])
#challenge = #track.challenges.where(id: params[:id]).first
end
tracks_controller.rb
def show
render json: #track, include: [:challenges]
end
private
def set_track
#track = Track.find(params[:id])
end
rails_server
For challenges => the wrong one
Started GET "/tracks/3/challenges/20/" for 127.0.0.1 at 2017-07-31 12:24:19 +0200
ActiveRecord::SchemaMigration Load (0.5ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ChallengesController#show as */*
Parameters: {"track_id"=>"3", "id"=>"20"}
Track Load (0.4ms) SELECT "tracks".* FROM "tracks" WHERE "tracks"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
Challenge Load (0.3ms) SELECT "challenges".* FROM "challenges" WHERE "challenges"."track_id" = ? AND "challenges"."id" = ? ORDER BY "challenges"."id" ASC LIMIT ? [["track_id", 3], ["id", 20], ["LIMIT", 1]]
Startup Load (0.4ms) SELECT "startups".* FROM "startups" ORDER BY "startups"."id" ASC LIMIT ? [["LIMIT", 1]]
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Class (0.18ms)
Completed 200 OK in 63ms (Views: 19.3ms | ActiveRecord: 2.6ms)
For tracks
Started GET "/tracks/222" for 127.0.0.1 at 2017-07-31 12:30:37 +0200
Processing by TracksController#show as */*
Parameters: {"id"=>"222"}
Track Load (0.2ms) SELECT "tracks".* FROM "tracks" WHERE "tracks"."id" = ? LIMIT ? [["id", 222], ["LIMIT", 1]]
Startup Load (0.3ms) SELECT "startups".* FROM "startups" ORDER BY "startups"."id" ASC LIMIT ? [["LIMIT", 1]]
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash (0.16ms)
Completed 404 Not Found in 6ms (Views: 4.1ms | ActiveRecord: 0.5ms)
You have defined #challenge like below
#challenge = #track.challenges.where(id: params[:id]).first
where returns nil if there is no record matching the condition. That is why you get null instead of 404 not found.
Whereas find in contrast returns 404 not found if the record doesn't exist.
If you want to get 404 not found, then modify #challenge like below
#challenge = #track.challenges.find(params[:id])
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
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
My create method does not take any parameters, rather it uses a sister object to assign the values. The fields are almost the same, but not quite.
I would also like to make the create method simpler (instead of doing a .new and then .save).
I would like the code below to be my starting point
controller
def create
design_setting = DesignSetting.first
primer3_parameter = Primer3Parameter.new
primer3_parameter.update_attributes(design_setting.attributes)
primer3_parameter.save
render json: primer3_parameter, root: false
end
def safe_params
params.permit(:generated, :status, :p3_file_id, :p3_file_flag,
...etc...
model
class Primer3Parameter < ActiveRecord::Base
has_many :batch_details
end
error
Started POST "/api/primer3_parameters" for 10.0.2.2 at 2014-06-11 23:15:38 +0200
Processing by Api::Primer3ParametersController#create as JSON
Parameters: {"base"=>{}}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
DesignSetting Load (1.1ms) SELECT "design_settings".* FROM "design_settings" ORDER BY "design_settings"."id" ASC LIMIT 1
(0.2ms) BEGIN
(0.3ms) ROLLBACK
Completed 500 Internal Server Error in 350ms
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes for Primer3Parameter: type, id):
app/controllers/api/primer3_parameters_controller.rb:12:in `create'
EDIT
After refactoring as suggested below the same error appears:
Started POST "/api/primer3_parameters" for 10.0.2.2 at 2014-06-11 23:27:25 +0200
Processing by Api::Primer3ParametersController#create as JSON
Parameters: {"base"=>{}}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
DesignSetting Load (1.2ms) SELECT "design_settings".* FROM "design_settings" ORDER BY "design_settings"."id" ASC LIMIT 1
Completed 500 Internal Server Error in 172ms
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes for Primer3Parameter: type, id):
app/controllers/api/primer3_parameters_controller.rb:12:in `create'
EDIT 2
Version 2 of the code
def create
design_setting = DesignSetting.first
primer_attributes = design_setting.attributes.except(:id, :created_at, :updated_at, :type)
primer_attributes = design_setting.dup
Rails.logger.debug("attributes #{primer_attributes}")
primer3_parameter = Primer3Parameter.create(primer_attributes)
render json: primer3_parameter, root: false
end
Started POST "/api/primer3_parameters" for 10.0.2.2 at 2014-06-11 23:33:21 +0200
Processing by Api::Primer3ParametersController#create as JSON
Parameters: {"base"=>{}}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
DesignSetting Load (1.5ms) SELECT "design_settings".* FROM "design_settings" ORDER BY "design_settings"."id" ASC LIMIT 1
attributes #<DesignSetting:0x0000000cca1988>
Completed 500 Internal Server Error in 163ms
NoMethodError (undefined method `stringify_keys' for #<DesignSetting:0x0000000cca1988>):
app/controllers/api/primer3_parameters_controller.rb:14:in `create'
EDIT 3
def create
design_setting = DesignSetting.first
primer_attributes = design_setting.attributes.except(:id, :type, :created_at, :updated_at)
primer3_parameter = Primer3Parameter.create(primer_attributes)
render json: primer3_parameter, root: false
end
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes for Primer3Parameter: type, id):
app/controllers/api/primer3_parameters_controller.rb:12:in `create'
EDIT4
This table has a lot of fields, so not all are pasted below.
I did notice something - the id is the last column, not the first. But it should not matter?
DesignSetting Load (1.3ms) SELECT "design_settings".* FROM "design_settings" ORDER BY "design_settings"."id" ASC LIMIT 1
parms: {"type"=>nil, "user_id"=>nil, "generated"=>nil, "status"=>nil, "p3_file_type"=>nil, "p3_file_id"=>"empty", "p3_file_flag"=>false, "p3_comment"=>"empty", "sequence_excluded_region"=>"empty", "sequence_force_left_end"=>nil
You can use the .except method on the attributes' hash:
primer3_parameter.update_attributes(design_setting.attributes.except(:id, :created_at, :updated_at, :type))
You can also refactor your create action to this:
def create
design_setting = DesignSetting.first
primer_attributes = design_setting.attributes.except(:id, :type, :created_at, :updated_at)
primer3_parameter = Primer3Parameter.create(primer_attributes)
render json: primer3_parameter, root: false
end
Ok this did it:
design_setting = DesignSetting.first
p = Primer3Parameter.new
p.attributes = design_setting.attributes.select{ |k, v| not %w{id type user_id created_at updated_at}.include?(k) }
p.save
Thank you #MrYoshiji for your help.
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.