Rails: undefined method `image' for nil:NilClass

I searched everywhere and found no solution at all. Here is my problem:

In my "Views" folder, I've "pins" and "pages folders.

In "views/pins/", I created a file named "_pin.html.erb" and inside it, I wrote this:

<%= image_tag pin.image(:medium) %>

Now to in my "views/pages" folder I've file named "home.html.erb" and inside it, I tried to render the code of "_pin.html.erb" using this:

<%= render "pins/pin" %>

but I'm getting this error:

undefined method `image' for nil:NilClass 
Extracted source (around line #1):
<%= image_tag pin.image(:medium) %>

So, what could be the problem? I'm using Paper clip and I tried to render the same code in "views/pins/index.html.erb using this:

<%= render @pins %>

and it is rendering perfectly but in "views/pages/home.html.erb" file (as mentioned above), I'm getting error!

Anyone can help me?

In my "models/pin.rb" file I've this:

class Pin < ActiveRecord::Base
  attr_accessible :description, :image

  validates :description, presence: true

  belongs_to :user
  has_attached_file :image
  validates :user_id, presence: true
  validates_attachment :image, presence: true,
                        content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']},
                        size: { less_than: 5.megabytes}
  has_attached_file :image, styles: { medium: "320x240"}
end

I tried my best to explain my problem, please tell me what I'm doing wrong? Thank you.

Upvotes: 0

Views: 2120

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Rails handle passing each pin into your collection automatically when using render @pins. If you want to use partial, you have to provide the collection to use like so:

<%= render partial: 'pins/pin', collection: @pins %>

Upvotes: 2

Related Questions