0

我正在创建一个允许用户登录、保持用户会话并允许用户创建任务的应用程序。每个任务都有一个所有者。任务应按所有者呈现(意味着用户只能看到他创建的任务)。

我的用户表包含:string name, string username, string password,我的任务表有 string title string body integer owner(应该是 user.id)

我已经定义了会话并且它们正在工作。在我的会话控制器中,我有一个方法可以将我重定向到主页,用户应该在该主页中看到他的所有任务(如果有任务)+ 创建新任务按钮或查看带有创建新任务按钮的空白页面

  def new
    if signed_in?
      redirect_to "/tasks/index"
    end
  end

我的任务/索引视图包含一个迭代任务(如果它们存在)并将它们呈现在屏幕上的方法

<h1>tasks</h1>
<%= link_to 'New Task', new_task_path %>
<ul>
  <% @tasks.each do |task| %>
  <li>
    <div>    
      <p><strong>Title:</strong>
      <%= task.title %></p>

    </div>
  </li>
  <% end %>
</ul>

和我的任务控制器:(我有一个编辑方法,我只是没有在这篇文章中输入它)

class TasksController < ApplicationController
  before_action :set_task, only: [:show, :update, :destroy]

  def index
    @tasks = Task.all
  end

  def show
  end

  def new
    @task = Task.new
  end

  def edit
  end

  def create
    @task = Task.new(task_params)

    respond_to do |format|
      if @task.save
        format.html { redirect_to @task, notice: 'Task was successfully created.' }
        format.json { render action: 'show', status: :created, location: @task }
      else
        format.html { render action: 'new' }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @task.destroy
    respond_to do |format|
      format.html { redirect_to tasks_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_task
      @task = Task.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def task_params
      params.require(:task).permit(:title, :user_id, :content)
    end
end

我的路线

 resources :tasks
  resources :users
  resources :sessions, only: [:new, :create, :destroy]
  root  'sessions#new'
  match '/new',  to: 'users#new',  via: 'get'
  match '/signin',  to: 'sessions#new',         via: 'get'
  match '/signout', to: 'sessions#destroy',     via: 'delete'

当我将用户发送到任务/索引时,我收到以下错误

Couldn't find Task with id=index

    # Use callbacks to share common setup or constraints between actions.
    def set_task
      @task = Task.find(params[:id])
    end

我的数据库是空的,我希望看到带有创建任务按钮的空页面。任何想法为什么我会收到此错误?

4

1 回答 1

1

如果您使用资源来创建路由,那么您应该使用 tasks_path 方法重定向到任务控制器中的索引操作:

def new
  if signed_in?
    redirect_to tasks_path   #Or, "/tasks"
  end
end

您可以阅读有关 Rails 路由架构的信息:http: //guides.rubyonrails.org/routing.html

于 2013-10-05T04:48:30.130 回答