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 trialWellington Alan
915 PointsProblem with associations
Hi, I'm using rails 4.0.4 and I'm getting problem when I try associate two tables. I have a table call Rooms with an user_id field and another table call Users. I created the migration and the association, but when I put an user_id on rooms form, rails is not saving the user_id on table Rooms.
Could anyone help me??
Thank you
1 Answer
Brandon Barrette
20,485 PointsStrong parameters. You should google this and see how Rails 4 handles this (it's different than the videos).
Here's a good explanation: http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html
Basically, you have to "permit" the fields you want the controller to have access to. If you don't permit them, then the controller doesn't know they exist. This is why your db column is empty.
Alternatively, you can do something like (Note: this assumes you are using Devise):
@room = current_user.rooms.new(params[:rooms])
This will automatically connect the association. This of course assumes that in your models you have:
#User.rb
has_many :rooms
#Room.rb
belongs_to :user
Wellington Alan
915 PointsWellington Alan
915 PointsI followed the instructions above, but now I got the follow error:
undefined method `rooms' for nil:NilClass
emiliakubokirschenbaum
8,816 Pointsemiliakubokirschenbaum
8,816 PointsThe undefined method is saying that it cant find the current_user, not the rooms