【发布时间】:2015-09-05 17:14:25
【问题描述】:
我正在使用设备进行身份验证。用户可以有很多相册。我有相册控制器和视图。我也有照片模型。
关联是用户可以有很多相册,相册可以有很多照片。 我正在为表格照片使用嵌套属性。使用载波进行照片上传。在创建新相册期间,我可以在 new.html.erb 视图中上传新照片。 能够在 edit.html.erb 视图中删除和更新照片。但我无法在 edit.html.erb 文件中上传新照片
这是相册控制器
class AlbumsController < ApplicationController
before_action :authenticate_user!
这些是控制器操作
def index
@albums = current_user.albums.all
end
def show
@album = current_user.albums.find(params[:id])
end
def new
@album = current_user.albums.new
@album.photos.new
3.times { @album.photos.build }
end
def edit
@album = current_user.albums.find(params[:id])
end
def create
@album = current_user.albums.build(album_params)
if @album.save
redirect_to action: 'index'
else
render 'new'
end
end
def update
@album = current_user.albums.find(params[:id])
if @album.update(album_params)
@album.save
redirect_to action: 'show'
else
render 'edit'
end
end
def destroy
@album = current_user.albums.find(params[:id])
@album.destroy
redirect_to action: 'index'
end
private
def album_params
params.require(:album).permit(:title,:description
photos_attributes[:id,:avatar,:_destroy])
end
end
这是用于创建新专辑的 new.html.erb 文件
<h1>New Album</h1>
<%= form_for @album, as: :album, url: user_albums_path, multipart: true
do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
用于照片上传
<p>
<%= f.fields_for :photos do|i| %>
<%= i.file_field :avatar %>
<% end %>
</p>
<p>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.submit %>
</p>
<% end %>
这是我创建编辑视图的edit.html.erb
<h1> Edit Your Album </h1>
这是编辑相册的表格
<%= form_for @album, as: :album, :url=> {:controller => "albums",:action
=> "update" }, method: :put do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
<p>
<table style="width:100%">
<tr>
<td>
<% for photo in @album.photos %>
<%= image_tag photo.avatar_url.to_s %>
<% end %>
</td>
</tr>
<tr>
<td>
<%= f.fields_for :photos do |builder| %>
<%= builder.check_box :_destroy %>
<%= builder.label :_destroy, "remove" %>
<% end %>
</td>
</tr>
</table>
</p>
<h3>Update</h3>
<p>
<%= f.fields_for :photos do|i| %>
<%= i.file_field :avatar %>
<% end %>
</p>
<p>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back',user_albums_path %>
这是album.rb,我在其中定义了嵌套属性和销毁属性。 该模型与用户模型有很多关联。
class Album < ActiveRecord::Base
has_many :photos, :dependent => :destroy
belongs_to :user
accepts_nested_attributes_for :photos, allow_destroy: true,
:update_only =>true
end
这是照片模型的 photo.rb 文件,我在其中定义了使用 carreirwave 创建的命名头像的装载上传器 这个模型与专辑有很多关联
class Photo < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
belongs_to :album
end
请告诉我如何在编辑操作期间上传新照片
【问题讨论】:
标签: ruby-on-rails