我无法表达我所面临的确切问题,但我会尝试使用简短的描述和代码。
我正在尝试向一个简单的现有应用程序添加一个功能,该应用程序允许用户为头像裁剪上传的图像。我在允许用户更新密码和其他各种帐户选项的同一视图上进行文件选择。用户提交该表单,然后呈现裁剪功能的视图。问题是从裁剪视图来看,提交失败是因为它未能验证前一个表单中的参数。基本上,我希望所有表单都同时提交,但来自两个不同的视图。
用户.rb
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :avatar,
:crop_x, :crop_y, :crop_w, :crop_h
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
mount_uploader :avatar, AvatarUploader
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
after_update :crop_avatar
def crop_avatar
avatar.recreate_versions! if crop_x.present?
end
end
我尝试了几种不同的方法来解决这个问题。我确信我错过了一个基本概念。有任何想法吗?
users_controller.rb
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
if params[:user][:avatar].present?
render 'crop'
else
sign_in @user
redirect_to @user, notice: "Successfully updated user."
end
else
render 'edit'
end
end
编辑.html.erb
<% provide(:title, "Edit user") %>
<h1>Update your profile</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for @user, :html => {:multipart => true } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :avatar %>
<%= f.file_field :avatar %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
作物.html.erb
<% provide(:title, 'Crop Avatar') %>
<h1>Crop Avatar</h1>
<div class="row">
<div class="span6 offset3">
<%= image_tag @user.avatar_url(:large), id: "cropbox" %>
<h4>Preview</h4>
<div style="width:100px; height:100px; overflow:hidden">
<%= image_tag @user.avatar.url(:large), :id => "preview" %>
</div>
<%= form_for @user do |f| %>
<% %w[x y w h].each do |attribute| %>
<%= f.hidden_field "crop_#{attribute}" %>
<% end %>
<div class="actions">
<%= f.submit "Crop" %>
</div>
<% end %>
</div>
</div>