是否通过控制器将当前用户id保存到db在ruby on rails上创建一个错误的选择?

Lon*_*Guy 2 ruby rubygems ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我的创建操作中的第3行是否被视为不良做法?由于用户有很多photo_albums和专辑需要链接到正确的用户我基本上抓住从CURRENT_USER的ID,并将其存储在我的photo_albums数据库表的user_id列.

我确信这应该从模型中完成,例如before_save或before_create我无法使其工作.我创建了一个带有参数的方法,并试图通过控制器将current_user id传递给该方法,然后在我的模型中写入该方法,然后在保存之前提供该方法名称,但我得到错误的参数数量错误或未定义的方法.

有人可以解释我是如何做到这一点非常感谢的.

  def create
    @photoalbum = PhotoAlbum.new(params[:photo_album])
    @photoalbum.user_id = current_user.id
    if @photoalbum.save
      flash[:notice] = "Successfully created gallery."
      redirect_to @photoalbum
    else
      render :action => 'new'
    end
  end
Run Code Online (Sandbox Code Playgroud)

亲切的问候

Mat*_*udy 7

这没有什么不对,但我倾向于让它更具体.

你说一个用户 has_many :photo_album

相反,我们可以说

  def create
    @photoalbum = current_user.photo_albums.build(params[:photo_album])
    if @photoalbum.save
      flash[:notice] = "Successfully created gallery."
      redirect_to @photoalbum
    else
      render :action => 'new'
    end
  end
Run Code Online (Sandbox Code Playgroud)

这实现了同样的目的,但使用has_many使我们的意图更加清晰.