Rails 3:保存方法不会工作
我正在构建我的第一个Rails应用程序,直到现在一切正常,但后来我发现以下场景:一个演示文稿应该有N个迭代。我没有使用REST。所以,我试图做一个简单的表单来创建迭代。Rails 3:保存方法不会工作
这些机型:
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"
问题是,保存方法不会保存,但@ iteration.errors.count的视图上的值是0. 我用然后保存!相反,当我在另一篇文章中读到时,以这种方式抛出以下错误:
验证失败:需要演示。
我搞不清楚我做错了什么。请注意,在我曾经有过“f.hidden_field”而不是“hidden_field_tag”的视图中,但是出于其他一些原因我改变了它,但是在此之前我得到了同样的错误。
你HAML,
hidden_field_tag :presentation_id
需求是,
f.hidden_field :presentation_id, :value => @presentation.id
我尝试了f.hidden_field,但仍然收到相同的错误。 – 2013-03-17 20:23:11
我已经更新了添加'value'属性的答案。 – Sam 2013-03-17 20:26:30
我试过你的解决方案,但同样的错误...我发现如果我做了像@ iteration.presentation = Presentation.find之类的东西,那么它实际上是有效的。我的意思是,这就像表单传递的对象从不附加到任何表示= / – 2013-03-17 20:29:55
看着你可以有你的模型定义,
嵌套资源:请参阅Controller path for nested resource - undefined method `<controller>_path'
- 个
利用虚拟属性:非常有用railcasts瑞恩在此 - >http://railscasts.com/episodes/16-virtual-attributes-revised
保存在会议演示ID:(这不是一个干净的非常干净的方法)
在你的控制器,你将需要在演示文稿中实例化迭代,以便呈现ID正确填充。
我注意到没有任何属性到达控制器... – 2013-03-17 20:34:00