has_many :gallery_images のギャラリーを持つアプリがあります
Ryan Batesの railscastをフォローしたところ、複数の画像をアップロードできました。私が直面している問題は、create.js.erb ファイルを取得してページを自動更新することです。これが私が得たものです。
gallery.rb
class Gallery < ActiveRecord::Base
has_many :gallery_images, dependent: :destroy
end
gallery_images.rb
class GalleryImage < ActiveRecord::Base
belongs_to :gallery
has_attached_file :image,
:styles => { :original => "1600x1600>",
:thumb => "100x100#" },
:default_url => "/images/:style/missing.png"
validates_attachment :image,
:presence => true,
:content_type => { :content_type => ['image/jpeg'] }
end
gallery_images_controller.rb
class GalleryImagesController < ApplicationController
def create
if signed_in?
@gallery = Gallery.friendly.find(params[:gallery_id])
@image = @gallery.gallery_images.create(gallery_image_params)
redirect_to gallery_path(@gallery)
else
@gallery = Gallery.friendly.find(params[:gallery_id])
redirect_to signin_url, notice: "Please sign in to add an image."
session[:return_to] = gallery_path(@gallery)
end
end
def destroy
@gallery = Gallery.friendly.find(params[:gallery_id])
@image = @gallery.gallery_images.find(params[:id])
@image.destroy
flash[:notice] = "Image removed."
redirect_to gallery_path(@gallery)
end
private
def gallery_image_params
params.require(:gallery_image).permit(:image)
end
end
ビュー/ギャラリー/show.html.erb
<div id="links">
<%= render @gallery.gallery_images %>
</div>
<% if current_user && current_user.admin? %>
<%= render "gallery_images/form" %>
<% end %>
ビュー/gallery_images/_form.html.erb
<%= form_for [@gallery, @gallery.gallery_images.new], html: { multipart: true } do |f| %>
<%= f.label :image, "Upload Image:" %>
<%= f.file_field :image, multiple: true, name: "gallery_image[image]" %>
<% end %>
javascripts/gallery_images.js.coffee
jQuery ->
$('#new_gallery_image').fileupload()
dataType: "script"
ビュー/gallery_images/create.js.erb
<% if @image.new_record? %>
alert("Failed to upload image");
<% else %>
$("#links").append("<%= j render(@image) %>");
<% end %>
助けてくれてありがとう。