Rectangle 27 35

This is solution to upload multiple images using carrierwave in rails 4 from scratch

rails new multiple_image_upload_carrierwave
gem 'carrierwave'
bundle install
rails generate uploader Avatar
rails g scaffold post title:string
rails g scaffold post_attachment post_id:integer avatar:string

rake db:migrate
class Post < ActiveRecord::Base
   has_many :post_attachments
   accepts_nested_attributes_for :post_attachments
end
class PostAttachment < ActiveRecord::Base
   mount_uploader :avatar, AvatarUploader
   belongs_to :post
end
def show
   @post_attachments = @post.post_attachments.all
end

def new
   @post = Post.new
   @post_attachment = @post.post_attachments.build
end

def create
   @post = Post.new(post_params)

   respond_to do |format|
     if @post.save
       params[:post_attachments]['avatar'].each do |a|
          @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
       end
       format.html { redirect_to @post, notice: 'Post was successfully created.' }
     else
       format.html { render action: 'new' }
     end
   end
 end

 def update
   respond_to do |format|
     if @post.update(post_params)
       params[:post_attachments]['avatar'].each do |a|
         @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
       end
     end
  end

  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to @post }
      format.json { head :no_content }
    end
  end


 private
   def post_params
      params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
   end
<%= form_for(@post, :html => { :multipart => true }) do |f| %>
   <div class="field">
     <%= f.label :title %><br>
     <%= f.text_field :title %>
   </div>

   <%= f.fields_for :post_attachments do |p| %>
     <div class="field">
       <%= p.label :avatar %><br>
       <%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>
     </div>
   <% end %>

   <% if params[:controller] == "post" && params[:action] == "edit" %> 
     <% @post.post_attachments.each do |p| %>
       <%= image_tag p.avatar, :size => "150x150" %>
     <% end %>
   <% end %>

   <div class="actions">
     <%= f.submit %>
   </div>
<% end %>
<p id="notice"><%= notice %></p>

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<% @post_attachments.each do |p| %>
  <%= image_tag p.avatar_url, :size => "150x150" %>
  <%= link_to "Destroy", p, method: :delete %>
<% end %>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

In rails 3 no need to define strong parameters and as you can define attribute_accessible in both the model and accept_nested_attribute to post model because attribute accessible is deprecated in rails 4.

Great post @SSR, only multiple upload I've managed to get working. Don't suppose you'd be able to expand it slightly? In it's current form the files aren't deleted when the parent model is. (Or don't for me), and I'm wondering how I'd go about editing the post and it's attachments together.

Essentially I'm wondering what the post_controller.rb would look like to correctly edit and delete the attachments?

thanks, it helps me I meant the idea!

Carrierwave, Rails 4, and Multiple Uploads - Stack Overflow

ruby-on-rails upload carrierwave
Rectangle 27 1

CarrierWave doesn't support multiple uploads. It's designed to associate a single file with a single field.

If you want multiple uploads, you need either multiple fields (each with a CarrierWave uploader), or multiple objects each with a single CarrierWave uploader field.

The multiple attribute is also unsupported, so if you use it, it's entirely up to you to get the parameters assigned properly.

That is not true. it support multiple upload within single field. see my answer. carrierwave provides much more.

Just to be clear: Your solution uses multiple objects (post_attachments), each with a single uploader, and demonstrates the manual work necessary to get parameters assigned properly for use of the "multiple" attribute. You've demonstrated how to do what the OP wanted, but it doesn't make any part of the above false.

Time progresses ever onwards. The Earth spins and gradually changes, and CarrierWave now supports multiple-file upload natively. However the CarrierWave way of doing it is an ugly hack (referencing all the files in one field using an array) that I would avoid using. Go with SSR's solution instead.

Carrierwave, Rails 4, and Multiple Uploads - Stack Overflow

ruby-on-rails upload carrierwave
Rectangle 27 4

I had the same problem and I found that you have to call 'remove_images!' if this was the last one. In 'remove_image_at_index' function add:

@gallery.remove_images! if remain_images.empty?

Looks plausible. Using Paperclip for my new app and won't be able to check this out anytime soon. I"ll try and think of it when I do, thanks anyway.

arrays - Rails 5 CarrierWave, can't remove last file in a multiple upl...

arrays carrierwave ruby-on-rails-5
Rectangle 27 6

Also I figured out how to update the multiple file upload and I also refactored it a bit. This code is mine but you get the drift.

def create
  @motherboard = Motherboard.new(motherboard_params)
  if @motherboard.save
    save_attachments if params[:motherboard_attachments]
    redirect_to @motherboard, notice: 'Motherboard was successfully created.'
  else
    render :new
  end
end


def update
  update_attachments if params[:motherboard_attachments]
  if @motherboard.update(motherboard_params)
    redirect_to @motherboard, notice: 'Motherboard was successfully updated.'
  else
   render :edit
  end
end

private
def save_attachments
  params[:motherboard_attachments]['photo'].each do |photo|
    @motherboard_attachment = @motherboard.motherboard_attachments.create!(:photo => photo)
  end
end

 def update_attachments
   @motherboard.motherboard_attachments.each(&:destroy) if @motherboard.motherboard_attachments.present?
   params[:motherboard_attachments]['photo'].each do |photo|
     @motherboard_attachment = @motherboard.motherboard_attachments.create!(:photo => photo)
   end
 end

Thanks for sharing your code. when you get time please update code at my gihub repo and do not forget to comment for each method so everyone can easily understand code.

Have you had a chance to give me access?

Rails 4 multiple image or file upload using carrierwave - Stack Overfl...

ruby-on-rails-4 carrierwave
Rectangle 27 42

Coming in Rails 4

In Rails 4, a chainable ActiveRecord::NullRelation will be returned from calls like Post.none.

The returned ActiveRecord::NullRelation inherits from Relation and implements the Null Object pattern. It is an object with defined null behavior and always returns an empty array of records without quering the database.

ruby on rails - How to return an empty ActiveRecord relation? - Stack ...

ruby-on-rails activerecord relation
Rectangle 27 177

This is solution to upload multiple images using carrierwave in rails 4 from scratch

rails new multiple_image_upload_carrierwave
gem 'carrierwave'
bundle install
rails generate uploader Avatar
rails generate scaffold post title:string
rails generate scaffold post_attachment post_id:integer avatar:string

rake db:migrate
class Post < ActiveRecord::Base
   has_many :post_attachments
   accepts_nested_attributes_for :post_attachments
end
class PostAttachment < ActiveRecord::Base
   mount_uploader :avatar, AvatarUploader
   belongs_to :post
end
def show
   @post_attachments = @post.post_attachments.all
end

def new
   @post = Post.new
   @post_attachment = @post.post_attachments.build
end

def create
   @post = Post.new(post_params)

   respond_to do |format|
     if @post.save
       params[:post_attachments]['avatar'].each do |a|
          @post_attachment = @post.post_attachments.create!(:avatar => a)
       end
       format.html { redirect_to @post, notice: 'Post was successfully created.' }
     else
       format.html { render action: 'new' }
     end
   end
 end

 private
   def post_params
      params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
   end
<%= form_for(@post, :html => { :multipart => true }) do |f| %>
   <div class="field">
     <%= f.label :title %><br>
     <%= f.text_field :title %>
   </div>

   <%= f.fields_for :post_attachments do |p| %>
     <div class="field">
       <%= p.label :avatar %><br>
       <%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>
     </div>
   <% end %>

   <div class="actions">
     <%= f.submit %>
   </div>
<% end %>

To edit an attachment and list of attachment for any post. In views/posts/show.html.erb

<p id="notice"><%= notice %></p>

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<% @post_attachments.each do |p| %>
  <%= image_tag p.avatar_url %>
  <%= link_to "Edit Attachment", edit_post_attachment_path(p) %>
<% end %>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
<%= image_tag @post_attachment.avatar %>
<%= form_for(@post_attachment) do |f| %>
  <div class="field">
    <%= f.label :avatar %><br>
    <%= f.file_field :avatar %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
def update
  respond_to do |format|
    if @post_attachment.update(post_attachment_params)
      format.html { redirect_to @post_attachment.post, notice: 'Post attachment was successfully updated.' }
    end 
  end
end

In rails 3 no need to define strong parameters and as you can define attribute_accessible in both the model and accept_nested_attribute to post model because attribute accessible is deprecated in rails 4.

For edit an attachment we cant modify all the attachments at a time. so we will replace attachment one by one, or you can modify as per your rule, Here I just show you how to update any attachment.

in the show action of the post controller i think you've forgot @post =Post.find(params[:id])

@SSR Why you looping through each post attachments in create action? Rails and carrierwave are smart enough to save collections automatically.

:_destroy

When I add validations to the post_attachment model, they do not prevent the post model from saving. Instead the post is saved, and then the ActiveRecord invalid error is thrown for the attachment model only. I think this is because of the create! method. but using create instead just fails silently. Any idea how to have the validation happen on the post reach into the attachments?

Rails 4 multiple image or file upload using carrierwave - Stack Overfl...

ruby-on-rails-4 carrierwave
Rectangle 27 34

So there are a few issues here.

First, Paperclip's has_attached_file method isn't an association to many files. It looks like you're trying to build an "asset" as if it's a Rails association. All Paperclip does is put a couple of fields into your table to store some meta-data about the file and you get one attached file per declaration of has_attached_file. If you want to attach 5 files, you would need to do something like:

has_attached_file :asset1
has_attached_file :asset2
has_attached_file :asset3
has_attached_file :asset4
has_attached_file :asset5

OR, alternatively, you could create another model just to store the files. For example:

class Listing < ActiveRecord::Base
  has_many :assets
end

class Asset < ActiveRecord::Base
  belongs_to :listing
  has_attached_file :picture
end

That way, you could have multiple assets attached to one listing (you didn't say what the original object was so I just called it "listing").

Second, there is no such thing as a multiple file upload in HTML (and, as such, the file_field method doesn't take a :multiple => true argument. You'll have to use something beyond Rails built-in form handling if you want multiple-file upload. Uploadify is a decent choice (that I've used before). There is a gem that will transform file fields to use uploadify (and will support the :multiple => true syntax that you want): https://github.com/mateomurphy/uploadify_rails3/wiki. However, I cannot vouch for how good it is.

My advice would be to start step-by-step. Uploading via Flash to Rails can be a complicated process that involves dealing with the CSRF meta-tag and other fields in your form. Start by making a form that allows a user to upload one file and stores it through Paperclip. Then maybe break the has_attached_file declaration into another model so that you can have 1 or many files associated with a model (as shown in the multi-model code block above). Then try adding Uploadify or another alternative. Ernie Miller has a decent tutorial on integrating Uploadify: http://erniemiller.org/2010/07/09/uploadify-and-rails-3/.

To start, remember that has_attached_file can only attach one file. When you try calling @listing.assets there is no "assets". There is an asset. You need to create a separate model yourself and use Rails' associations if you want multiple files.

I already do have another model created called "Listing". A listing has_many assets. I already can upload multiple assets, just not through a single "Choose File" field. if anyone has any good examples using uploadify that'd be great. I'm not sure how to do the background JS to process each image and POST them to the server properly.

You can add :multiple => "multiple" to your file_field, that enables multiple file selection from one html file input field (at least in Chrome). I haven't solved the problem of managing these uploads properly yet, but I know that post parameter includes an array of the multiple files you have picked and uploaded.

:html => {:multipart => :true }
form_for

Just to add to this: i would move the file uploading to ajax, allowing you to gather a list of files from the user and then upload them one at a time in the background: this way it would appear to the user that they have uploaded lots of files at once, even though behind the scenes that's not what's happening. You can also set any other params for how the resulting records might need to be organised on the server. For file upload with ajax (jquery), which can be a bit tricky to get right, see eg abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

Rails Paperclip & Multiple File Uploads - Stack Overflow

ruby-on-rails file-upload amazon-s3 paperclip
Rectangle 27 4

I thought I would contribute back to the community by sharing how I solved this problem.

To summarize, the major problem was to reconcile the behavior of CarrierWave, nested forms, and fine grained control of file uploads.

The crux of the issue was that Nested Forms create the root record and all its associations in a single POST operation to the #create action of the root Controller.

In the example above, the Recording model was the root, while AudioFile, Note, and Categorization were the associations to be created along with a Recording.

So with Nested Forms, I would have to create all these records in a single POST, which would preclude the possibility of canceling uploads in isolation, or uploading in parallel with adding other fields (like Notes).

That would not make for a good user experience. My solution was really simple:

  • Recording#create would always be called with empty parameters. The Recording attributes would get sensible default values in the create operation.
  • The user would only see the Recording#edit page.
  • On the Recording#edit page, I had independent controls for CRUD operations on the associated models which would route to different controllers through AJAX calls. This worked because each associated model had a valid recording_id to use.
  • The various controllers would return HTML fragments which would be written into the main recording page.

This enabled inline editing of all the fields on the Recording page, even though these fields mapped to different (associated) models. Thus the user would be able to upload multiple files, add notes while they were uploading, play back already uploaded files, and cancel uploads at will.

As a result the whole user experience was a lot smoother. This would never have been achievable with Nested forms by definition.

Nested forms, inline uploads, and progress bars with Carrierwave in Ra...

ruby-on-rails progress-bar nested-forms carrierwave
Rectangle 27 27

If we take a look at CarrierWave's documentation, this is actually very easy now.

I will use Product as the model I want to add the pictures, as an example.

Get the master branch Carrierwave and add it to your Gemfile:

gem 'carrierwave', github:'carrierwaveuploader/carrierwave'

Create a column in the intended model to host an array of images:

rails generate migration AddPicturesToProducts pictures:json
  • Run the migration bundle exec rake db:migrate
app/models/product.rb

class Product < ActiveRecord::Base
  validates :name, presence: true
  mount_uploaders :pictures, PictureUploader
end

Add pictures to strong params in ProductsController

app/controllers/products_controller.rb

def product_params
  params.require(:product).permit(:name, pictures: [])
end
  • Allow your form to accept multiple pictures app/views/products/new.html.erb # notice 'html: { multipart: true }' <%= form_for @product, html: { multipart: true } do |f| %> <%= f.label :name %> <%= f.text_field :name %> # notice 'multiple: true' <%= f.label :pictures %> <%= f.file_field :pictures, multiple: true, accept: "image/jpeg, image/jpg, image/gif, image/png" %> <%= f.submit "Submit" %> <% end %>

In your views, you can reference the images parsing the pictures array:

@product.pictures[1].url

If you choose several images from a folder, the order will be the exact order you are taking them from top to bottom.

CarrierWave's solution to this problem makes me cringe. It involves putting all the references to the files into one field in an array! It certainly wouldn't be considered the "rails way". What if you then want to remove some, or add extra files to the post? I'm not saying it wouldn't be possible, I'm just saying it would be ugly. A join table is a much better idea.

That solutions is already provided by SSR. Another model is put in place to hold the uploaded file, then the thing that needs many files uploaded relates in a one-to-many or many-to-many relationship with that other model. (the join table I mentioned in my earlier comment would be in the case of a many-to-many relationship)

Thanks @Toby1Kenobi, I was wondering how the column array method would account for image versions (I don't see how it can). Your strategy is doable.

Rails 4 multiple image or file upload using carrierwave - Stack Overfl...

ruby-on-rails-4 carrierwave
Rectangle 27 25

I think that one solution can be to save the decoded data to file and then assign this file to mounted uploader. And after that get rid of that file.

The other (in-memory) solution can be this one:

# define class that extends IO with methods that are required by carrierwave
class CarrierStringIO < StringIO
  def original_filename
    # the real name does not matter
    "photo.jpeg"
  end

  def content_type
    # this should reflect real content type, but for this example it's ok
    "image/jpeg"
  end
end

# some model with carrierwave uploader
class SomeModel
  # the uploader
  mount_uploader :photo, PhotoUploader

  # this method will be called during standard assignment in your controller
  # (like `update_attributes`)
  def image_data=(data)
    # decode data and create stream on them
    io = CarrierStringIO.new(Base64.decode64(data))

    # this will do the thing (photo is mounted carrierwave uploader)
    self.photo = io
  end

end

i'm curious what the not in-memory solution would be? should i have concerns about performance with this solution?

how would image_data=(data) be called?

I'm using a data URL generated from a canvas. My final image was invalid. You have to make sure the data passed in is only the data, without the "data:image/png," part.

ruby - Rails Carrierwave Base64 image upload - Stack Overflow

ruby-on-rails ruby carrierwave
Rectangle 27 1

Add the relevant attributes to your model and introduce a before_save callback.

class Video < ActiveRecord::Base
  mount_uploader :video, VideoUploader

  before_save :update_video_attributes
  private

  def update_video_attributes
    if video.present? && video_changed?
      self.content_type = video.file.content_type
      self.file_size = video.file.size
    end
  end
end

Can I do this in carrierwave uploader too? do I have to set for each element a special column in table?

ruby on rails - carrierwave multiple file uploads and storing - Stack ...

ruby-on-rails ruby ruby-on-rails-4 carrierwave
Rectangle 27 10

Issue with multiple lines

ASS subtitles can have a semi-transparent background for the text.

  • Open your subtitles file with aegisub.
Subtitle
Styles manager
Current Script
Default
Edit
  • Experiment with the Outline and Shadow values. Check Opaque box.
  • Under Colors click the color under Outline or Shadows. A window will appear. Adjust the value of the Alpha box to change transparency.
  • Save the subtitles as an .ass file.

If you want hardsubs you can use the subtitles filter to add the transparent background with the force_style option.

If your subtitles contains multiple lines, due to auto-wrapping of long lines or an intentional line break, the backgrounds will overlap and potentially look ugly as shown below:

You can avoid this by:

Outline
Shadow
  • The alpha settings of the shadow will control the transparency of the background box. Click on the shadow color to adjust the Alpha of the shadow color to your desired transparency level.

Edit the ASS file in a text editor. In the Style line change the value corresponding with BorderStyle to 4. This will fill the bounding box background of each subtitle event. Example Style line:

Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H80000000,&H80000000,-1,0,0,0,100,100,0,0,4,0,0,2,10,10,10,1

Note that BorderStyle=4 is a non-standard value, so it may not work properly in all players.

BorderStyle

The drawbox filter can be used to create a background box. This may be useful if you want the box to span the width.

ffmpeg -i input -filter_complex "drawbox=w=iw:h=24:y=ih-28:t=max:color=black@0.4,subtitles=subs.ass" output

Downside is that you have to account for line breaks or word wrapping for long subtitles. Simply making the box taller to compensate will suffice, but will look ugly because the subtitles baseline remains static: the single line subtitles will have more padding on the top than the bottom.

This leaves a nasty line in there in case of two-line subtitles. Is there a way to ged rid if it?

@sup Not that I know of. An alternative method would be to make a static, transparent box using the drawbox filter, but that is not idea either.

@eusoubrasileiro Good to hear. Just be aware of the "multiple lines may overlap and look ugly" issue. IIRC, it's a problem with libass. There's a bug report about it somewhere.

@sup If I recall correctly it was on the Aegisub Bug Tracker, but it's currently down.

@LordNeckbeard Actually, setting BorderStyle=4 fixes the issue (see the Github issue I opened), would you please update your answer? It only works with libass though.

How to set background to subtitle in ffmpeg? - Stack Overflow

ffmpeg subtitle
Rectangle 27 30

As of Rails 4, you would do:

class Article < ActiveRecord::Base 
  has_many :comments, -> { order(created_at: :desc) }
end 
class Comment < ActiveRecord::Base 
  belongs_to :article 
end
has_many :through
class Article
  has_many :comments, -> { order('postables.sort' :desc) }, 
           :through => :postable
end

If you will always want to access comments in the same order no matter the context you could also do this via default_scope within Comment like:

class Comment < ActiveRecord::Base 
  belongs_to :article 
  default_scope { order(created_at: :desc) }
end

Before Rails 4 you could specify order as a key on the relationship, like:

class Article < ActiveRecord::Base 
  has_many :comments, :order => 'created_at DESC'
end

As Jim mentioned you can also use sort_by after you have fetched results although in any result sets of size this will be significantly slower (and use a lot more memory) than doing your ordering through SQL/ActiveRecord.

If you are doing something where adding a default order is cumbersome for some reason or you want to override your default in certain cases, it is trivial to specify it in the fetching action itself:

sorted = article.comments.order('created_at').all

Where can I specify it in the fetching action itself? Do I override a method in the model?

@Wit - you can add .order() to the method chain, like in the last example. Is this what you are asking?

How do I automatically sort a has_many relationship in Rails? - Stack ...

ruby-on-rails
Rectangle 27 1

try require 'mini_gmagick' instead of require 'mini_magick', graphics magick has only one executable gm, and by default mini_magick uses image magick, which has multiple binaries and identify is one of them.

ruby on rails - Mini Magick, GraphicMagick and Carrierwave - Stack Ove...

ruby-on-rails upload carrierwave image-uploading minimagick
Rectangle 27 7

CKEDITOR.editorConfig = function(config) {
  config.language = 'pl';
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";
  config.toolbar_Pure = [
    '/', {
      name: 'basicstyles',
      items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']
    }, {
      name: 'paragraph',
      items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']
    }, {
      name: 'links',
      items: ['Link', 'Unlink']
    }, '/', {
      name: 'styles',
      items: ['Styles', 'Format', 'Font', 'FontSize']
    }, {
      name: 'colors',
      items: ['TextColor', 'BGColor']
    }, {
      name: 'insert',
      items: ['Image', 'Table', 'HorizontalRule', 'PageBreak']
    }
  ];
  config.toolbar = 'Pure';
  return true;
};

and works as expected

javascript - Rails 4 ckeditor file upload - Stack Overflow

javascript ruby-on-rails ruby-on-rails-4 ruby-on-rails-3.2 ckeditor
Rectangle 27 3

Yes, you can call it API to track the end of a multiple upload process:

var $fileInput = $('#fileupload');

$fileInput.on('fileuploaddone', function(e, data) {
    var activeUploads = $fileInput.fileupload('active');
    /*
     * activeUploads starts from the max number of files you are uploading to 1 when the last file has been uploaded.
     * All you have to do is doing a test on it value.
     */
    if(activeUploads == 1) {
        console.info("All uploads done");
        // Your stuff here
    }
}

jquery - Finish of Multiple file upload - Stack Overflow

jquery file-upload blueimp
Rectangle 27 4

Just add photos_attributes to the attr_accessible list in the Product model. Or even better, try to migrate to strong_parameters gem, will save you sometime when you migrate to Rails 4.

In create action, you create a @photo variable from params[:photo], which is knows to return nil, yielding the object invalid always. That said, you don't need to create that variable as Photo objects are already made for as you use accepts_nested_attributes_for already. I understand that you need to know if the Photos are created successfully, but you shouldn't be worrying about it as errors from product's new photos will propagate to the product, stopping the saving process.

when i add :photos_attributes to product model attr_accessible i get an error that says Image can't be blank !!

in the beginning of the form i have - if @photo.errors.any? .error_messages %h2 Image is invalid

Can you please post the output of this line @photos.errors.full_messages? Or "image can't be blank" is it's output?

ruby - Rails - MassAssignmentSecurity:: Error on multiple photo upload...

ruby-on-rails ruby ruby-on-rails-3
Rectangle 27 511

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

last line listens for page load which is what turbo links will trigger.

var ready;
ready = function() {

  ...your javascript goes here...

};

$(document).ready(ready);
$(document).on('page:load', ready);

Edit 2...For Rails 5 (Turbolinks 5) page:load becomes turbolinks:load and will be even fired on initial load. So we can just do the following:

$(document).on('turbolinks:load', function() {

  ...your javascript goes here...

});

Is that coffee script? I haven't learned it yet. Is there a js or jQuery equivalent to your example?

var ready = function() { ... } $(document).ready(ready) $(document).on('page:load', ready)
.ready
'page:load'

@Emerson there is a very useful website, with an explicit name: js2coffee.org

I can confirm that the ready function does not get called twice. If it's a hard refresh, only the ready event is fired. If it's a turbolinks load, only the page:load event is fired. It's impossible for both ready and page:load to be fired on the same page.

FYI You can also apply this for multiple events page:load and ready by including a space-separated string for the first argumet. $(document).on('page:load ready', ready); The second argument is simply a function, which happens to be named ready, following this answer's example.

javascript - Rails 4: how to use $(document).ready() with turbo-links ...

javascript jquery ruby-on-rails-4 asset-pipeline turbolinks
Rectangle 27 509

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

last line listens for page load which is what turbo links will trigger.

var ready;
ready = function() {

  ...your javascript goes here...

};

$(document).ready(ready);
$(document).on('page:load', ready);

Edit 2...For Rails 5 (Turbolinks 5) page:load becomes turbolinks:load and will be even fired on initial load. So we can just do the following:

$(document).on('turbolinks:load', function() {

  ...your javascript goes here...

});

Is that coffee script? I haven't learned it yet. Is there a js or jQuery equivalent to your example?

var ready = function() { ... } $(document).ready(ready) $(document).on('page:load', ready)
.ready

doesn't it only get called when it needs to though? It calls it when the document is ready and then it calls it when the page loads (which we are assuming came from a turbo-link trigger). Right?

'page:load'

@Emerson there is a very useful website, with an explicit name: js2coffee.org

I can confirm that the ready function does not get called twice. If it's a hard refresh, only the ready event is fired. If it's a turbolinks load, only the page:load event is fired. It's impossible for both ready and page:load to be fired on the same page.

FYI You can also apply this for multiple events page:load and ready by including a space-separated string for the first argumet. $(document).on('page:load ready', ready); The second argument is simply a function, which happens to be named ready, following this answer's example.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Rails 4: how to use $(document).ready() with turbo-links ...

javascript jquery ruby-on-rails-4 asset-pipeline turbolinks
Rectangle 27 508

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

last line listens for page load which is what turbo links will trigger.

var ready;
ready = function() {

  ...your javascript goes here...

};

$(document).ready(ready);
$(document).on('page:load', ready);

Edit 2...For Rails 5 (Turbolinks 5) page:load becomes turbolinks:load and will be even fired on initial load. So we can just do the following:

$(document).on('turbolinks:load', function() {

  ...your javascript goes here...

});

Is that coffee script? I haven't learned it yet. Is there a js or jQuery equivalent to your example?

var ready = function() { ... } $(document).ready(ready) $(document).on('page:load', ready)
.ready
'page:load'

@Emerson there is a very useful website, with an explicit name: js2coffee.org

I can confirm that the ready function does not get called twice. If it's a hard refresh, only the ready event is fired. If it's a turbolinks load, only the page:load event is fired. It's impossible for both ready and page:load to be fired on the same page.

FYI You can also apply this for multiple events page:load and ready by including a space-separated string for the first argumet. $(document).on('page:load ready', ready); The second argument is simply a function, which happens to be named ready, following this answer's example.

javascript - Rails 4: how to use $(document).ready() with turbo-links ...

javascript jquery ruby-on-rails-4 asset-pipeline turbolinks