【问题标题】:Rails custom model methodRails 自定义模型方法
【发布时间】:2016-11-29 09:51:03
【问题描述】:

我有模型用户,我想在模型中创建一些方法,在助手中调用此方法,在控制器列表示例中并在视图中调用此助手,但是有错误并且不知道如何正确编写

我的模型用户和我的方法

  def include_current_user
    User.where.not(id: current_user.id)
  end

我的控制器列表和助手

  def shared_users
    @users ||= User.include_current_user
  end

  helper_method :shared_users

还有我的观点,调用助手

  <%= f.collection_check_boxes(:users, shared_users, :id, :email)%>

起伏错误

undefined method `include_current_user' for #<Class:0x007f389c649f98>
Did you mean?  included_modules

当我将我的方法移动到自我部分时 像这样:

  class << self  
    def include_current_user
      where.not(id: current_user.id)
    end
  end

有错误

undefined local variable or method `current_user' for #<Class:0x007f38ac5d98c8>
Did you mean?  current_scope

当前用户这是会话助手中的助手

  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

可能会为我的方法 include_current_user 添加变量并获取 像这样在行动中调用

  def shared_users
    @users ||= User.include_current_user(current_user)
  end

模型中的方法

  class << self  
    def include_current_user(user)
      where.not(id: user.id)
    end
  end

当创建一些查询时一切都很好,就像这样

  def shared_users
    @users ||= User.where.not(id: current_user.id)
  end

  helper_method :shared_users

但我想在模型中创建方法,可能更复杂,如何正确的方法?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
    1. 将方法include_current_user改为类方法

    2. 模型上不存在 current_user

    型号:

    def self.include_current_user current_user
       User.where.not(id: current_user.id)
    end
    

    控制器:

    def shared_users
      @users ||= User.include_current_user current_user
    end
    

    【讨论】:

    • 我将变量添加到方法中,但我有疑问 - 这是正确的方法吗?
    • 是的,current_user 只存在于会话中。这意味着您只能在视图或控制器上调用它
    【解决方案2】:

    include_current_user 不是类方法。因此,如果不引用 User 类的对象,就不能调用它。尝试将include_current_user 定义为self.include_current_user。这将使它成为一个类方法。然后您就可以将其称为User.include_current_user

    【讨论】:

    • 这仍然不能解决他的问题,因为当前用户在模型中不可用。 @shuba.ivan 您需要将当前用户传递给方法,并处理它为 nil 的可能性。
    • @j-dexx -- 他明确表示@users ||= User.where.not(id: current_user.id) 工作正常。这意味着current_user 可能已经在类级别定义。
    • 他说当前用户是一个助手。除非他包含它,否则它将在模型中不可用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多