How do you set an attribute when creating an ActiveRecord object?

别等时光非礼了梦想. 提交于 2019-12-11 01:36:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!