Reputation:
I have a web app which uses Devise for authentication. It is a site which allows the user to upload images so the url would be /images/2
. There is a separate image controller.
How would I go about showing the Users name on that image? I have put = user.name
to show the user name, this is HAML by the way. I have also tried = @user.name
= user.name
shows undefined local variable or method user for #<#<Class:0x007f8f9c28d2e0>:0x007f8f9c287f70>
= @user.name
shows undefined method name for nil:NilClass
Upvotes: 0
Views: 171
Reputation: 1120
Do you have an association between the image and the user that posted the image? Like this:
# image.rb
belongs_to :user
# user.rb
has_many :images
In that case you do not have to set the @user variable in your controller. You can access the owning user directly by using @image.user
in your view. To post the username you can chain it like this: @image.user.name
, even better would be to modify the to_s method of your user as shown below. This method gets called automatically if you try to display your object, so you could just display the name using @image.user
then.
# user.rb
def to_s
self.name
end
Upvotes: 1
Reputation: 7810
It seems that @user.name
fails because you are not setting the @user
variable to the correct value while your are in your image controller.
Try also whether current_user
returns you an instance. In other words, instead of = @user.name
try = current_user.name
.
I cannot give you more info. I have never worked with Devise
in the past.
Upvotes: 0