我创建了一个包含两个字段的小表单,并且将来打算使用一个或两个字段扩展此表单。事实证明,在sqlite中包含数据并没有完成,但没有给出任何错误。
该应用程序正在开发为待办事项列表。
你能告诉我可能的原因吗?
我有一个模特:
class ToDoList < ActiveRecord::Base
attr_accessible :is_favorite, :name, :description
has_many :tasks, dependent: :destroy
belongs_to :member
end
和控制器:
class ToDoListsController < ApplicationController
...
def new
@todo_list = ToDoList.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @todo_list }
end
end
...
def create
@todo_list = ToDoList.new(params[:todo_list])
respond_to do |format|
if @todo_list.save
format.html { redirect_to @todo_list, notice: 'Todo list was successfully created.' }
format.json { render json: @todo_list, status: :created, location: @todo_list }
else
format.html { render action: "new" }
format.json { render json: @todo_list.errors, status: :unprocessable_entity }
end
end
end
观点:new.html.erb
<h2> add new task</h2>
<%= render partial: 'to_do_list' %>
_to_do_list.httml.erb:
<%= form_for(@todo_list = ToDoList.new) do |f| %>
<%#= form_for(@todo_list) do |f| %>
<% if @todo_list.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@todo_list.errors.count, "error") %> prohibited this todo_list from being saved:</h2>
<ul>
<% @todo_list.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:0)
看起来您正在尝试批量分配属性。如果您正在使用Rails 4 attr_accessible被取消,您必须使用控制器中的强参数进行质量分配,请参阅https://stackoverflow.com/a/17371364/3197124。或者尝试在创建中单独分配单个参数,例如todo_list.name。
答案 1 :(得分:0)
谢谢,github的链接非常有用。
问题是进入的params哈希称为to_do_list
NOT todo_list
。因此,当您执行ToDoList.new(params[:todo_list]
时,您不会将任何内容映射到对象......您应该ToDoList.new(params[:to_do_list])
。
实际上,由于您的模型类是ToDoList,因此正确的下划线用法总是to_do_list
我建议你扫描到处使用过的地方&#34; todo_list&#34;或&#34; @ todo_list&#34;并将其更改为&#34; to_do_list&#34;和&#34; @ to_do_list&#34;。它不是绝对必要的,但为了保持一致性,它是人们期望看到的。
我已经确认可以解决您的问题。
干杯 史蒂夫