代码之家  ›  专栏  ›  技术社区  ›  Charles Smith

带有find和where的show方法中的rails 5自定义查询

  •  1
  • Charles Smith  · 技术社区  · 7 年前

    我为这个笨拙的问题道歉。我有一个索引方法,它将对象限制为 current_user 这很好,但我仍然可以在show方法中访问对象。

    这将只显示当前的用户对象

    def index
      @todo_lists = TodoList.where(user_id: current_user)
    end
    

    不幸的是,如果您知道id,这仍然允许访问该对象

    def show
      @todo_list = TodoList.find(params[:id])
    end
    

    我想做的只是 undefined method where 错误

    def show
      @todo_list = TodoList.find(params[:id]).where(user_id: current_user)
    end
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Sebastián Palma    7 年前

    你应该“替换”你当前的查询。因为find返回一个对象,即与被请求的模型/表对应的对象。where将在模型中使用,并返回 ActiveRecord::Relation ,这就是你需要找到你的身份证。

    之后,您可以使用find,它将查找单个实体(一条记录)并将其作为模型的实例返回。

    尝试:

    TodoList.where('user_id = ?', current_user).find(params[:id])
    

    注意,如果current_user是user的一个实例,假设它有许多产品,则可以使用该关联获取所有产品,然后找到所需的产品:

    current_user.todo_lists.find(params[:id])