Don P
Don P

Reputation: 63647

Rails association works when it doesnt use an instance variable

I'm getting the strangest error I've seen in Rails so far. In my view, I can print out the email associated with a painting if I find the record directly (e.g. Painting.find(15). But if I try to use an instance variable it errors (e.g @painting).

views/paintings/show.html.erb

<%= Painting.find(15).artist.user.email %>  # works
<%= @painting.artist.user.email %> # Error: "undefined method 'user' for nil:NilClass"

controllers/paintings_controller.rb

def show
  @painting = Painting.find(15)
end

Models: "users", "artists", "paintings".

  1. A user can be an artist. So a user has_one artist.

  2. An artist has_many paintings.

Upvotes: 1

Views: 71

Answers (2)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

I think you should add associations. This how they should look like:

class User < ActiveRecord::Base
  has_one :artist # it's ok
end

class Artist < ActiveRecord::Base
  belongs_to :user # add this
  has_many :paintings
end

class Painting < ActiveRecord::Base
  belongs_to :artist
end

For me both cases works with this associations.

Upvotes: 1

RubyNewbie
RubyNewbie

Reputation: 29

Use

def show
  @painting = Painting.find(15).last
end

Currently the second one is returning a 1 element array, but in order to call a dependent method, you must specify 1 item.

Upvotes: 0

Related Questions