我有模型用户,我想在模型中创建一些方法,在助手中调用此方法,在控制器列表示例,并调用此助手在视图中,但有错误,不知道如何正确写入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
但我想在模型中创建方法,可能会更复杂,如何做正确的方法?
我向方法和这项工作添加变量,但我有问题 - 这是正确的方式? –
是的,current_user只存在于会话中。这意味着你只能在视图或控制器上调用它 –