views:

168

answers:

2

I am trying to set an attribute on an object that I am creating. I feel like this should work:

 def create
    @album = Album.new(params[:album])
    @album.user = current_user

    if @album.save
       flash[:notice] = 'Album was successfully created for ' + current_user.login + '.'
       redirect_to albums_url 
    else
       render :action => "new"
    end
  end

But it seems to ignore the assignment to the user field. Any ideas?

+1  A: 

Did your Album migration or does your album model reference a user_id or a relationship to user?

If not, the database won't save that information even if you assign it.

Oliver N.
Well, that was embarrassing. I forgot to run the migration script to set up that relationship in the database. Thanks!
pkaeding
+4  A: 
John Topley
Yes, I do have the class hierarchy set up correctly. So, I should this in place of the call to Album.new? When I try that, I get undefined method `build' for #<User:0x353c3a4>
pkaeding
Sorry, there was a mistake in my code which I've corrected now. The build method is on the User's albums array. That scopes the new album to the albums belonging to that user i.e. populates the user_id field of the new album.
John Topley