I have this line on “routes.rb” => get ‘/home/add’ => ‘photos#add’, but the browser gives me this error
undefined local variable or method `user' for #<#<Class:0x007fe075485dc0>:0x007fe0738e8d38>
The question is, how can I call a method from a html.erb?.
Thank you so much, best regards.
Alfredo.
Second… try plan better your routes. It’s not related with your currently problem at all… but do you agree that it’s a bit odd to add a home for a photo? Does it not look natural to add a photo to an user?
so… looks more natural a route like :user/photo/add translated to user_photo_add(@user)
In the users/show.html.erb I’m using the following lines:
<% @photos.each do |product| %>
<%= @photo.user_id %>
<% end %>
In the user controller I have declare this : photos = Photo.order(:title), but the browser gives me this error:
undefined method `each' for nil:NilClass in the following line -> <% @photos.each do |product| %>
Could you please tell me what I'm doing wrong?.
Thank you and best regards.
I suggest you to study a little about ruby before starting with rails. This also is a “problem” about variable scope.
To use a variable in the view, it must be an instance variable, in your case:
@photos = Photo.order(:title)
and in the view you have 2 errors: |products| should be |photo| and inside the loop you must use the photo variable (which have a different value every cycle of the loop).
<% @photos.each do |photo| %>
<%= photo.user_id %>
<% end %>
Yeah sorry when I copy the text I didn't select the @. But with that the
issue stil there...
You should *always* copy/paste code when asking questions, otherwise
it just causes others to waste their time.
If I use
<% @photo.each do |photo| %>
That should be @photos not @photo, or are you retyping rather than
copy/paste again?
If you have used @photos in the view then first check development.log
where you should see the sql query being performed to pick up the
photos. If that looks ok then you can put some diagnostic code in the
controller after setting up @photos to check whether it is setup ok.
If you use puts in the controller it will appear in the server
terminal window.