问题
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:
Assuming that your model relationships are set up correctly*, it's better to do:
@album = current_user.albums.build(params[:album])
—This will correctly populate the user_id field for the new album to the ID of the current user.
*Something like:
class User < ActiveRecord::Base
has_many :albums
.
.
.
end
class Album < ActiveRecord::Base
belongs_to :user
.
.
.
end
回答2:
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.
来源:https://stackoverflow.com/questions/753379/how-do-you-set-an-attribute-when-creating-an-activerecord-object