Im working on a rails app where a user has the ability to upload photos. When a user uploads their photos it will appear on their profile. Everything works great besides when there is no photos created then I am unable to view the user profile page because of the photo being nil.
here is my show method in the users_controller.rb
def show
@user = User.find_by_id(:id)
@photo = @user.photos.find(params[:id])
end
Here is my show.html.erb
<% for photo in @user.photos %>
<%= photo.title %>
<%= photo.description %>
<%= image_tag photo.image_url(:thumbnail) %>
<%= link_to "Show", photo %>
<br>
<% end %>
How can I bypass this error?
The code for your action seems wrong…
It should be this:
I commented out the third line on purpose, because I’m not sure what it is you want to do there, yet.
The
@uservariable needs to be defined usingparams[:id], given that this is theshowaction for theUsersController, so the id for the user will be passed through asparams[:id].But then you go and use this to find the photo for the user, which is what confuses me… the
Photorecord’sidattribute is probably not going to be the same as theUserrecord’sidattribute.So what is it?