如何让用户只使用ruby和sinatra查看他们的列表

时间:2016-11-07 21:04:34

标签: ruby sinatra

我的ruby和sinatra应用程序目前允许用户查看和编辑创建的所有列表,但我还无法弄清楚如何只向创建它们的用户显示列表。

这是我的lists_controller的样子:

class ListsController < ApplicationController 

 get "/lists" do
  redirect_if_not_logged_in
  @lists = List.all
  erb :'lists/index'
 end

 get "/lists/new" do
  redirect_if_not_logged_in 
  @error_message = params[:error]
  erb :'lists/new'
 end

 get "/lists/:id/edit" do
  redirect_if_not_logged_in 
  @error_message = params[:error]
  @list = List.find(params[:id])
  erb :'lists/edit'
 end

 delete '/lists/:id/delete' do
  @list = List.find_by_id(params[:id])
  @list.delete
  redirect to '/lists'
 end

 post "/lists/:id" do
  redirect_if_not_logged_in 
  @list = List.find(params[:id])
  unless List.valid_params?(params)
    redirect "/lists/#{@list.id}/edit?error=invalid list"
  end
  @list.update(params.select{|a|a=="todo_name"|| a=="todo_list"})
  redirect "/lists/#{@list.id}"
 end

 get "/lists/:id" do
  redirect_if_not_logged_in 
  @list = List.find(params[:id])
  erb :'lists/show'
 end

 post "/lists" do
  redirect_if_not_logged_in 
  unless List.valid_params?(params)
    redirect "/lists/new?error=invalid list"
  end
  List.create(params)
  redirect "/lists"
 end
end

1 个答案:

答案 0 :(得分:0)

问题在于

@lists = List.all

在带有ActiveRecord的Rails中(假设您的List模型belongs_toUser),您可以改为执行

@lists = List.where(user_id: current_user.id)