我正在构建我的第一个 Rails 应用程序,直到现在一切都很好,但后来我发现了以下场景:一个演示文稿应该有 N 次迭代。我没有使用 REST。所以,我试图制作一个简单的表格来创建迭代。
这些是模型:
class Presentation < ActiveRecord::Base
has_many :iterations
end
class Iteration < ActiveRecord::Base
belongs_to :presentation
attr_accessible :presentation_id, :description, :delivery_date, :file
validates :presentation_id, :presence => {:message => 'is required.'}
end
这些是控制器中的操作:
#Shows Form
def add
@iteration = Iteration.new
@presentation = Presentation.find(params[:id])
end
#Saves Form
def save
@iteration = Iteration.new(params[:iteration])
@iteration.delivery_date = Time.now
if @iteration.save
flash[:notice] = "Saved succesfully!"
else
flash[:error] = "Changes were not saved."
end
redirect_to root_url
end
这些将是 HAML 中的视图:
= form_for @iteration, :url => { :action => "save", :method => "post" }, :html => { :multipart => true } do |f|
- if @iteration.errors.any?
There were some errors:
.notice-text.fg-color-white
%ul.notice
- for message in @iteration.errors.full_messages
%li= message
%br
.field
= f.label :description, "Description"
= f.text_area :description, :class=>"form-text-area", :rows=>5
.field
= f.label :file, "Upload File"
= f.file_field :file
.field
= hidden_field_tag :presentation_id, @presentation.id
%br
= f.submit "Save"
问题是,save 方法不会保存,但是视图上@iteration.errors.count 的值为0。我用了然后保存!相反,正如我在另一篇文章中所读到的那样,它会引发以下错误:
验证失败:需要演示。
我无法弄清楚我做错了什么。请注意,在视图中,我曾经使用“f.hidden_field”而不是“hidden_field_tag”,但我出于其他原因更改了它,但是在此之前我遇到了同样的错误。