0

だから私はRailsに不慣れで、現在のユーザーに基づいて非常に単純なto doリストを作成しようとして、それをいじっていました。これまでのところ、認証は Devise で処理され、フォームは simple_form gem でレンダリングされます。データベースに新しいタスクを追加しようとするまで、すべてが正常に機能します。なんらかの理由で、フォームを送信すると、db 列に NULL が入力されます (もちろん、増加する id 列を除く)...送信中に値が失われたり、何かがおかしいようです。とにかく、ここに私が持っているものがあります:

コントローラ:

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 %

それはおそらく本当に単純なことで、私はそれを見つけることができないようです. どんな助けでも大歓迎です。

4

1 に答える 1

2

コントローラーの create メソッドでは、params は

params[:todo]

それよりも

params[:task]

そのパラメーターの名前は、変数の名前ではなく、インスタンスのモデル名によって決定されます。

致命的なことは何もありませんが、モデルが異なる方法で関連付けられているインスタンス変数に名前を付けることは、ベストプラクティスではなく、後で多くの混乱を招く可能性があります。

于 2012-11-19T05:35:33.323 に答える