我正在构建一个Rails应用程序,我需要用户在注册表单上上传个人资料图片/具有个人资料照片的图像编辑功能。 Carrierwave应该正确安装,到目前为止Devise似乎运行良好。当我上传照片然后点击"创建个人资料"时,它只会刷新到同一页面并每次重置文件上传字段。
SOLUTION:将控制器中的更新方法更新为:
def update
@pet = Pet.find(params[:id])
if @pet.update(pet_params)
redirect_to pets_path
else
render :edit
end
end
已在我的app / uploaders / profile_photo_uploader.rb文件中上传:
class ProfilePhotoUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
我有一个&#34; profile_photo&#34;我的架构中的字符串也是。
我的控制器创建和编辑/更新操作在这里:
def create
@pet = Pet.new(pet_params)
if @pet.save
flash[:notice] = 'Your pet profile was saved!'
redirect_to pets_path
else
flash.now[:notice] = 'Your pet profile could not be saved.'
render :new
end
end
def show
@pet = Pet.find(params[:id])
end
def edit
@pet = Pet.find(params[:id])
end
def update
@pet = Pet.find(params[:id])
if @pet.save
redirect_to pets_path
else
render :edit
end
end
def pet_params
params.require(:pet).permit(:name, :breed, :age,
:color, :weight, :personality, :favorite_things, :owner_id, :profile_photo)
end
使用SimpleForm的新表单:
<h1>New Pet Profile</h1>
<%= simple_form_for @pet, html: { multipart: true } do |f| %>
<%= f.input :name, required: true, label: "Pet Name:" %>
<%= f.input :profile_photo, type: :file %>
...
<%= f.button :submit %>
<% end %>
路线:
Rails.application.routes.draw do
devise_for :owners
resources :pets
resources :owners do
resources :pets, shallow: true
end
end
应用程序控制器:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :profile_photo
end
end
答案 0 :(得分:1)
您需要将模型设置为app/models/pet.rb
class Pet < ActiveRecord::Base
validates_presence_of :profile_photo
belongs_to :owner
mount_uploader :profile_photo, ProfilePhotoUploader
end
另外,请注意,如果您使用Heroku,它不会保存图片,因为它是静态服务。您需要将Cloudinary与Carrierwave等服务集成在一起。
在表单行<%= simple_form_for @pet, html: { multipart: true } do |f| %>
之后将其放入
<% if @pet.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@pet.errors.count, "error") %> prohibited this pet from being saved:</h2>
<ul>
<% @pet.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
此行<%= f.input :profile_photo, type: :file %>
到此<%= f.file_field :profile_photo %>
在pet_controller文件的末尾,请确保您已获得表单提交数据的权限
def pet_params
params.require(:pet).permit(:name, :profile_photo)
end
由于我看到您正在使用设计,您可以考虑将所有者分配给宠物。考虑pet_controller.rb
def create
@pet = Pet.new(pet_params)
@pet.owner = current_user
并查看模型belongs_to :owner