2012-11-18 35 views
0

所以我是Rails的新手,我一直在嘗試基於當前用戶創建一個非常簡單的待辦事項列表。到目前爲止,我使用Devise處理身份驗證,並使用simple_form gem呈現表單。一切工作正常,直到我嘗試添加一個新的任務到數據庫。由於某種原因,當我提交表單時,它將NULL輸入到db列中(當然除了遞增的id列之外)......這就好像值在傳輸中或者奇怪的東西中迷失了一樣。總之,這裏是我有:Rails Simple_Form在數據庫中將NULL值保存爲NULL

控制器:

class TodoController < ApplicationController 
    before_filter :authenticate_user! 

    def index 
    @todo_list = Todo.where("user_id = ?", current_user.id).all 
    @task = Todo.new 
    end 

    def create 
    @todo_list = Todo.all 
    @task = Todo.new(params[:task]) 
    if @task.save 
     flash[:notice] = "Task Added" 
     redirect_to todos_path 
    else 
     render :action => 'index' 
    end 
    end 

    def destroy 
    @todo_list = Todo.find(params[:id]) 
    @task.destroy 
    flash[:notice] = "Task Deleted" 
    redirect_to todos_path 
    end 
end 

型號:

class Todo < ActiveRecord::Base 
    belongs_to :users 
    attr_accessible :user_id, :task_name, :task_description 
end 

查看:

<h2>To Do List</h2> 
<%= render :partial => 'form' %> 

<div class="span11"> 
<table class="table table-condensed table-striped"> 
     <thead> 
     <tr> 
      <th>Task</th> 
      <th>Description</th>   
     </tr> 
    </thead> 
    <tbody> 
    <% @todo_list.each do |todo| %> 
    <tr> 
     <td><%= todo.task_name %></td> 
     <td><%= todo.task_description %></td> 
     <td><%= link_to("Delete", todos_path, :confirm => 'Delete task?', :method => :delete, :class => 'btn btn-mini') %></td> 
    </tr> 
    <% end %> 
</table> 
</div> 

_form.html.erb:

<%= simple_form_for @task, :url => todos_path, :method => :post do |f| %> 
    <%= f.error_notification %> 
    <%= f.input :task_name, :as => :string %> 
    <%= f.input :task_description, :as => :string %> 
    <%= f.button :submit, :class => 'btn btn-success' %> 
<% end % 

這可能是非常簡單的事情,我似乎無法發現它。任何幫助,將不勝感激。

+1

你可以發佈你的rails日誌的輸出嗎?至少,我認爲在保存到'create'之前,你必須先放上'@todo.user = current_user'這樣的東西。 – mccannf

+1

你不需要指定:url和:method,只要把'<%= simple_form_for @task do | f | %>' – Thanh

回答

2

在您的控制器的創建方法,不應該PARAMS是

params[:todo] 

而不是

params[:task] 

該參數的時名稱由您的實例的型號名稱規定,不你說什麼變量。

沒有什麼致命的,但是命名實例變量時,有一個模型綁定的模型不是最好的做法,可能會導致以後很多混淆。

+0

非常感謝!這種改正適用於我。 – Desmond

相關問題