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 trialalborz
Full Stack JavaScript Techdegree Graduate 30,885 PointsGetting 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
36,441 PointsAlright, this means your @link is nil - it was not found or created properly. Make sure that @link contains a proper Link class object.
Maciej Czuchnowski
36,441 PointsLooks 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
Full Stack JavaScript Techdegree Graduate 30,885 PointsI 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.
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Pointsalborz
Full Stack JavaScript Techdegree Graduate 30,885 PointsIn 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
36,441 PointsMaciej Czuchnowski
36,441 PointsBut 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.
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Pointsalborz
Full Stack JavaScript Techdegree Graduate 30,885 PointsGot it - thanks!