Ruby on rails 模型:未定义的局部变量或方法“当前用户';

Ruby on rails 模型:未定义的局部变量或方法“当前用户';,ruby-on-rails,devise,rails-admin,Ruby On Rails,Devise,Rails Admin,我不熟悉Rails,Rails\u管理和设计。尝试在模型中获取当前用户(我认为应该由Desive提供): class Item < ActiveRecord::Base attr_accessible :user_id belongs_to :user, :inverse_of => :items after_initialize do if new_record? self.user_id = current_user.id unles

我不熟悉Rails,Rails\u管理和设计。尝试在模型中获取当前用户(我认为应该由Desive提供):

class Item < ActiveRecord::Base
  attr_accessible :user_id
  belongs_to :user, :inverse_of => :items

  after_initialize do
    if new_record?      
      self.user_id = current_user.id unless self.user_id
    end                                
  end  
end
我看到config/initializers/rails_admin.rb中有一行,但不确定它是做什么的:

  config.current_user_method { current_user } # auto-generated

您不能在模型中引用当前用户,因为它仅对控制器和视图可用。这是因为它是在ApplicationController中定义的。解决此问题的方法是在控制器中创建项时设置该项的用户属性

class ItemsController < Application Controller

  def create
    @item = Item.new(params[:item])
    @item.user = current_user # You have access to current_user in the controller
    if @item.save
      flash[:success] = "You have successfully saved the Item."
      redirect_to @item
    else
      flash[:error] = "There was an error saving the Item."
      render :new
    end
  end
end
class ItemsController
此外,为了确保在未设置用户属性的情况下不会保存项目,您可以对用户id进行验证。如果未设置,项目将不会保存到数据库

class Item < ActiveRecord::Base
  attr_accessible :user_id
  belongs_to :user,
             :inverse_of => :items # You probably don't need this inverse_of. In this
                                   # case, Rails can infer this automatically.

  validates :user_id,
            :presence => true
end
class项:items#您可能不需要这个inverse_of。在这个
#在这种情况下,Rails可以自动推断出这一点。
验证:用户\u id,
:presence=>true
结束

验证本质上解决了当您使用after_initialize回调在模型中设置用户时尝试执行的操作。保证在没有该信息的情况下不会保存项目。

当前用户不属于模型。这个答案有一些解释


当前用户仅在控制器/视图中定义,是否有任何方法使其在模型中也可用?或者这是一个安全问题?模型不应该意识到这一点,这不是他们的责任,而是你的全面答案。我使用的是Rails_Admin,希望在管理控制台中输入数据(有时是数百行)时设置这些属性(而不是每次创建新行时手动选择)。乍一看,Rails_管理控制器似乎不可访问。也许有一种方法可以覆盖它。Rails_Admin的功能更像是构建在Rails之上的数据库管理系统,而不是直接与数据库交互。但不幸的是,该功能只会发展到目前为止,无法处理控制器中的所有应用程序逻辑。
class ItemsController < Application Controller

  def create
    @item = Item.new(params[:item])
    @item.user = current_user # You have access to current_user in the controller
    if @item.save
      flash[:success] = "You have successfully saved the Item."
      redirect_to @item
    else
      flash[:error] = "There was an error saving the Item."
      render :new
    end
  end
end
class Item < ActiveRecord::Base
  attr_accessible :user_id
  belongs_to :user,
             :inverse_of => :items # You probably don't need this inverse_of. In this
                                   # case, Rails can infer this automatically.

  validates :user_id,
            :presence => true
end