I am getting this error:
[code]
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
[/code]
In controller:
#optionals = Car.find_all_by_car_id(1)
In view:
<% #optionals.each do |c| %>
<div><%= c.type %></div>
<% end %>
In the table Car is one row... so I don't understand, how is possible to getting this error message... I tried to search on google, but unfortunately I still don't know how to fix this error...
So I'll glad for each help!
EDIT: car_id in table Cars have the value 1
Try adding a line in the template like so:
<%= #optionals.inspect %> and make sure it's not nil.
If it is, check the log to make sure the action that you're calling matches the template you're looking at
Related
Im building a basic chat room website with multiple chat rooms that users can comment on.
I managed to get my messages/comments to show up on each Room.show page, however when I go to enter
<p><%= message.user.name if message.user %> <small><em><%= "#{time_ago_in_words(message.created_at)} ago" %></em></small></p>
I receive a nil can't be converted to a Time value error. Also, I cannot get the Users name to show up. It just registers blank.
Here is the section of my Room.show.html.erb that is registering an error
<% #message.each do |message| %>
<div class="row">
<p><%= message.user.name if message.user %> <small><em><%= "#{time_ago_in_words(message.created_at)} ago" %></em></small></p>
<p><%= message.body %></p>
</div>
<% end %>
Here is my Message controller
def show
#rooms = Room.all
#message = #room.message
end
Here is my Routes file
Rails.application.routes.draw do
devise_for :users
#resources :messages
resources :users
resources :rooms do
resources :messages
end
root 'rooms#index'
end
Message.rb
class Message < ApplicationRecord
belongs_to :user
belongs_to :room
end
And room.rb
class Room < ApplicationRecord
has_many :message
end
Using updated version of rails.
message.created_at is nil. You can verify it by changing your code slightly:
<%= "#{time_ago_in_words(message.created_at || Time.now)} ago" %>
This will always show less than a minute ago because message.created_at is nil.
<%= "#{time_ago_in_words(message.created_at)} ago" if message.created_at %>
This will not show anything because message.created_at is nil.
I suggest that you use a debugging library like pry to help you troubleshoot this. You could do something like this:
<% #message.each do |message| %>
<div class="row">
<% binding.pry unless message && message.created_at %>
<p><%= message.user.name if message.user %> <small><em><%= "#{time_ago_in_words(message.created_at)} ago" %></em></small></p>
<p><%= message.body %></p>
</div>
<% end %>
That will set a breakpoint that will be triggered if message or message.created_at are nil, and allow you to use the Rails console to inspect the variables to help narrow down the problem.
Like others mentioned, you will need to make sure your models are appropriately constructed:
class Room < ApplicationRecord
has_many :messages
end
You should also check your schema.rb to ensure that the Message model has the following:
t.datetime "created_at", null: false
t.index ["room_id"], name: "index_messages_on_room_id"
The first is needed because without it message.created_at will not exist at all, and the second is needed for the association between the two models.
Your controller code doesn't make any sense and I'm assuming that you manually typed it into your question rather than copying and pasting it. You define #rooms as an ActiveRecord::Relation collection object, but you call #room.message. If you meant #rooms.message then that won't work because you're trying to call an instance method on a collection. I'm not sure what you meant here because the code doesn't make sense.
Additionally, you're not implementing a clean CRUD solution. Your Messages controller's show method should be for rendering a single Message object, not for rendering a collection of rooms' messages.
In general there are many problems with the code, the structure, and the example you have typed out. At the very least though, you must make sure that message.created_at is not nil before attempting to call time_ago_in_words, and that all traces back to:
making sure your models are correctly formed and associated with each other
making sure your controller is fetching real objects
making sure your view is appropriately iterating over those real objects
I want to print specific value from object result. here is i am execute SQL query and take all data from View tables, All data coming from "Employee_Information" view(table).
hr_controller.rb
class HrController < ApplicationController
def internal_employee_page
#employees = MysqlConnection.connection.select_all("SELECT * FROM Employee_Information")
end
end
internal_employee_page.html.erb this is my first view
<div id="job_details">
<% #employees.each do |emp| %>
<%= render partial: "hr/employee_details", locals: {emp: emp} %>
<% end %>
</div>
_employee_details.html.erb this is my second view
<h3> User Name : <%= emp%> </h3>
like this I am trying to print all value
then I got following result
I want to print each value
I tried this also in my second view
<h3> User Name : <%= emp.full_name%> </h3>
But I got Error:
Please help me I tried every thing according to my knowledge, where am I wrong and what is problems
Try this:
<h3> User Name : <%= emp["full_name"] %> </h3>
you are trying to read values from Hash,so emp.full_name will not work, you can read value from hash like Hash['key']
so for full_name do <%= emp['full_name'] %>
<h3> User Name : <%= emp.full_name%> </h3>
full_name is not an attribute of employee instance that's why you got this error. try fetch specific attribute which is present in that employee instance.
Right now your response objects are just simple Hash objects and to access the values for keys you would need to use Hash methods such as [] or fetch to retrieve the values. If you would like more method like syntax you could do one of the following:
Use ActiveRecord or another ORM mapper
Create Dynamic or Static classes yourself and map the results to them
Monkey Patch Hash with something like method_missing to fake this concept
I'm learning to use Carrierwave the first step is obviously to upload a picture and see if it's effectively inserted to the database. One detail that could be important is that this code is written in a Rails Engine and namespaced (Wanker)
I generated an uploader following the instruction of the gem, everything went good (Wanker::PicturesUploader)
I made a model CompanyDetailImage with a picture string field (MySQL) and added this line
mount_uploader :picture, Wanker::PicturesUploader
Then I made a view and a form
<%= f.fields_for [:wanker, #company, #company_detail, #company_detail_images] %>
<%= i.label :picture %>
<%= i.file_field :picture %>
<% end %>
The params[:company][:company_detail_image]["picture"] in the controller will have this inside of it
[#<ActionDispatch::Http::UploadedFile:0x007fe613b81f40
#content_type="image/png",
#headers=
"Content-Disposition: form-data; name=\"company[company_detail_image][picture][]\"; filename=\"Screen Shot 2015-02-04 at 8.18.58 PM.png\"\r\nContent-Type: image/png\r\n",
#original_filename="Screen Shot 2015-02-04 at 8.18.58 PM.png",
#tempfile=# <File:/var/folders/2w/lw3glw5d58g25qvv4cx6yk0m0000gn/T/RackMultipart20150213-22947-np2et6>>]
Which for me seemed good. But when I try this
#company_detail_image = Wanker::CompanyDetailImage.new
#company_detail_image.picture = params[:company][:company_detail_image]["picture"]
#company_detail_image.save!
It returns this
ActiveRecord::RecordInvalid: Validation failed: Picture You are not allowed to upload nil files, allowed types: jpg, jpeg, gif, png
Does someone has an idea why it doesn't catch the picture ? Thank you guys ;)
Try this:
#company_detail_image.picture = params[:company][:company_detail_image]["picture"].first
This is because your ["picture"] param is returning an array rather than the object itself (which is the first item in that array).
I'm trying to have a drop down list but when i try it it give me
undefined method `collect' for nil:NilClass
the controller:
def existing
#courses = Course.all
end
def duplicate
course = Course.find_by_id(permitd_up[:id])
new_course = course.dup
if new_course.save
redirect_to :action => 'show'
else
redirect_to :back
end
end
the view:
<h3>Choose a Course</h3>
<%= form_for :course , url: {:action => "duplicate" , method: "post"} do |f|%>
<%= f.select :id , #courses.collect{|c| [c.id , c.name]} %>
<br><br>
<%= f.submit%>
<%end%>
You will receive the following error
undefined method `collect' for nil:NilClass
on
<%= f.select :id , #courses.collect{|c| [c.id , c.name]} %>
Only when #courses instance variable was not set in the action that rendered this particular view.
I see that #courses variable is set in the existing method. If you are using existing as an action which renders this view then your view name must be existing.html.erb.
Or if you are rendering the view from a different action then in that case you should set #courses value in that particular action by either directly setting the value within action OR by calling existing method from there.
If you have your courses as a database table, you might want to try using rails' built in field helper collection_select. It will populate your select field with all of the data available in your model. If you want a drop-down like the one you are describing, I believe using collection select is the best way to handle it.
You can read up on it here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
Alternatively, if you have a ton of courses, maybe try looking into using a text field with autocomplete. Jquery UI has a plugin that makes this very easy. You can check out the railscasts for it here: http://railscasts.com/episodes/102-auto-complete-association-revised.
It requires a pro account but if you do a lot of rails developing it will be the best $9 you spend every month.
If you would like to continue to do it this way, make sure that you are defining
#courses = Courses(:all) in the correct controller action, otherwise you will have nothing to render.
I have HTML code in my Rails application that looks like this:
<td><%= MyObj.find_by_id(#my_obj.some_id).name %></td>
And this shows up fine. However, the field some_id is not always present in the database, so I'd like to display NA rather than MyObj's name in those cases.
So here's what I mean in pseudocode:
<td><%= IF #my_obj.some_id is NIL THEN "NA" ELSE MyObj.find_by_id(#my_obj.some_id).name %></td>
How can I do this?
You can use the following snippet:
<td><%= #my_obj.some_id.present? ? MyObj.find(#my_obj.some_id).name : 'NA' %></td>
However, you're exposing yourself to some pretty big issues if you're finding records in your view code like this. Your controller should handle that kind of logic.
You should not be hitting the database in your view code, leave that to your controllers. Try loading the object in your controller instead:
# use this code to your controller
#view_obj = MyObj.find_by_id(#my_obj.some_id)
You can then use the try method to set the name, which will return nil instead of raising the usual NoMethodError if the object is nil:
<%= #view_obj.try(:name) || "NA" %>
<%= !MyObj.find_by_id(#my_obj.some_id).name.blank? ? MyObj.find_by_id(#my_obj.some_id).name : "NA" %>