【发布时间】:2015-07-09 00:54:00
【问题描述】:
每个用户都有_one 个字符。每个Character has_one :profilepicture,属于Picturething 类,它持有一个Carrierwave mount_uploader 来上传单张图片。每个字符都有_many :standardpictures,也属于 Picturething 类。图片上传在views/users/edit中处理,在users_controller中点击update_pictures方法。
我们的想法是一次上传一张标准图片。好像可以了,Rails 控制台 > Picturething.all 显示一个新的 Picturething 已经添加到数据库中,并且在页面上正确显示。这旨在成为 character.standardpictures 之一。
奇怪的是,不知怎的,在整个过程中,角色的 :profilepicture 也被设置为上传的同一张图片。我不明白这是怎么回事。在任何时候我都没有代码说“@character.profilepicture = standardpicture”,但不知何故,它决定第一个 :standardpicture 和 :profilepicture 是一个相同的。如果 profilepicture 存在,但它不应该存在,它会显示在 edit.html.erb 页面上,我有 <% if @character.profilepicture.nil? %> 行。它在这里显示上传的图片,所以很明显 profilepicture 不是 nil,但应该是。
这是怎么回事?
字符.rb:
has_many :standardpictures, class_name: "Picturething", dependent: :destroy
accepts_nested_attributes_for :standardpictures
has_one :profilepicture, class_name: "Picturething", dependent: :destroy
accepts_nested_attributes_for :profilepicture
picturething.rb:
class Picturething < ActiveRecord::Base
belongs_to :character
mount_uploader :picture, CharacterpicUploader
validate :picture_size
end
app/views/users/edit.html.erb:
<%= form_for :standardpicture, url: update_pictures_user_path,
method: :post, html: { multipart: true } do |f| %>
<%= f.label :picture %>
<%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>
<%= f.submit "Upload pictures", class: "btn btn-primary" %>
<% end %>
routes.rb:
post '/users/:callsign/update_pictures', to: 'users#update_pictures', as: :update_pictures_user
users_controller.rb:
def update_pictures
@character = Character.find_by(callsign: params[:callsign])
@user = @character.sociable
@standardpicture = @character.standardpictures.build(update_pictures_user_params)
if @standardpicture.save
flash[:success] = "Pictures updated"
redirect_to(edit_user_path(@user))
else
redirect_to(edit_user_path(@user))
end
end # update_pictures
def update_pictures_user_params
params.require(:standardpicture).permit(:picture)
end
返回 app/views/users/edit.html.erb:
<% if @character.profilepicture.nil? %>
<p>Select a picture below to use as your profile picture</p>
<% else %>
<%= image_tag @character.profilepicture.picture %>
<% end %>
【问题讨论】: