我正在处理一个嵌套表单,用户在创建屏幕时还应该附加一个图像(一个名为 Screenshot 的单独模型)。在将新屏幕保存到数据库之前,我正在尝试验证附件是否存在。我试图在 Screenshot 模型中验证附件是否存在,但只有 precent Screenshot 被保存,而它仍然创建一个 Screen。
这是我的模型:
class Screen < ActiveRecord::Base
belongs_to :project
has_many :screenshots
validates :name, presence: true
accepts_nested_attributes_for :screenshots
validates_presence_of :screenshots
end
class Screenshot < ActiveRecord::Base
belongs_to :screen
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
这是我的控制器:
def create
@screen = Screen.create(screen_params)
if @screen.save
flash[:notice] = "A new screen has been added to this project"
redirect_to [@screen.project]
else
render :action => 'new'
end
end
最后是我的表格:
<%= form_for ([@project, @screen]), :html => { :multipart => true } do |f| %>
<% if @screen.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@screen.errors.count, "error") %> prohibited this screen from being saved:</h2>
<ul>
<% @screen.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.hidden_field :project_id %>
</div>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= f.fields_for :screenshots, @screen.screenshots.build do |s| %>
<%= s.hidden_field :screen_id, :value => @screen.id %>
<%= s.hidden_field :version, :value => "1" %>
<%= s.label :image %><br>
<%= s.file_field :image %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
非常感谢对这个菜鸟的任何帮助。