2016-11-29 84 views
0

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

我的模型用户和我的方法

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 

当前用户这是ssesion帮手帮手

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 

也许NNED行动调用添加变量我的方法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 

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

回答

2
  1. 改变方法include_current_user类方法

  2. CURRENT_USER上模型

模型不存在:

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

CONTRO ller:

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

我向方法和这项工作添加变量,但我有问题 - 这是正确的方式? –

+0

是的,current_user只存在于会话中。这意味着你只能在视图或控制器上调用它 –

0

include_current_user不是类方法。因此,如果没有提到User类的对象,就不能称它。尝试将include_current_user定义为self.include_current_user。这将使它成为一种类方法。然后你可以将其称为User.include_current_user

+0

这仍然不会解决他的问题,因为当前用户将不会在模型中可用。 @ shuba.ivan您需要将当前用户传入方法,并处理它为零的可能性。 –

+0

@ j-dexx - 他明确表示“@users || = User.where.not(id:current_user.id)”工作正常。这意味着'current_user'可能已经在类级别上定义。 – 31piy

+0

他说现在的用户是帮手。除非包含模型,否则模型将不可用。 –