mysql - Rails Simple_Form 在数据库中将值保存为 NULL

标签 mysql ruby-on-rails devise simple-form

所以我是 Rails 的新手,我一直在尝试根据当前用户创建一个非常简单的待办事项列表。到目前为止,我已经使用 Devise 处理了身份验证,并使用 simple_form gem 呈现表单。一切工作正常,直到我尝试向数据库添加新任务。由于某种原因,当我提交表单时,它会在 db 列中输入 NULL(当然除了递增的 id 列)...就像值在传输中丢失或出现奇怪的情况一样。无论如何,这就是我所拥有的:

Controller :

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 %

这可能是非常简单的事情,我只是似乎无法发现它。任何帮助将不胜感激。

最佳答案

在 Controller 的创建方法中,参数不应该是

params[:todo]

而不是

params[:task]

该参数的名称由实例的模型名称决定,而不是您为变量命名的名称。

没有什么致命的,但命名具有不同模型的实例变量并不是最佳实践,可能会在以后导致很多困惑。

关于mysql - Rails Simple_Form 在数据库中将值保存为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13445739/

相关文章:

mysql - 无法重新创建mysql用户

php - 管理员搜索查询

mysql - 来自 TSV 文件的 Seed Rails 数据库 (MySQL)

ruby-on-rails - 使用带有 RSpec 的设计测试 View

ruby-on-rails - Rails 6 Heroku 设计错误 ActiveSupport::MessageEncryptor::InvalidMessage

ruby-on-rails - 如何在 rspec 功能测试中访问(设计)current_user?

mysql - 对所有条目求和,然后将其与值进行比较

php - 不同的在sql查询中不起作用

javascript - 尝试设置限制时,rails jquery 自动完成功能不起作用

ruby-on-rails - 使用 Rails Omniauth gem 和 Google OpenID 时如何不需要用户的电子邮件