Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

alborz
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Points

Getting an undefined method error when using Rails console

Hi - I'm making a Reddit clone app via https://www.youtube.com/watch?v=7-1HCWbu7iU&t=1078 (around the 29:05 mark in the video) and when I type @link.user = User.first I get the following error:

User Load (33.9ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 NoMethodError: undefined method `user=' for nil:NilClass

How can I solve this? Thanks!

2 Answers

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Alright, this means your @link is nil - it was not found or created properly. Make sure that @link contains a proper Link class object.

alborz
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Points

In my Links controller I have for the def new method: @link = current_user.links.build; and for the def create method: @link = current_user.links.build(link_params) followed by what was generated by the scaffold. I'm wondering what I'm missing?

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

But in your console you first have to instantiate this @link element - Rails doesn't know what you mean just by typing @link. It's just an empty (nil) variable. You'd have to do something like "@link = Link.new" and then do the .user stuff with it.

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Looks like you're missing something like "belongs_to :user" in your link model. That basically gives you a user getter and user= setter. I assume you also have a user_id field in your links schema.

alborz
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Points

I do; I added a user_id field to the links table via migration. I also have a model association between the link and the user models as you mentioned.