i want to put index image to my blog's posts
and have an upload form in 'new post 'in admin's panel
the form is written like this :
- error = #post.errors.include?(:file)
%fieldset.control-group{:class => error ? 'has-error' : ''}
=f.label :file, :class => 'control-label'
.controls
=f.file_field :file ,:name => 'file'
- error = #post.errors.include?(:title)
%fieldset.control-group{:class => error ? 'has-error' : ''}
=f.label :title, :class => 'control-label'
.controls
=f.text_field :title, :class => 'form-control input-large input-with-feedback', :autofocus => true
%span.help-inline=error ? f.error_message_on(:title, :class => 'text-error') : pat(:example)
- error = #post.errors.include?(:body)
%fieldset.control-group{:class => error ? 'has-error' : ''}
=f.label :body, :class => 'control-label'
.controls
~f.text_area :body, :class => 'form-control input-large input-with-feedback'
%span.help-inline=error ? f.error_message_on(:body, :class => 'text-error') : pat(:example)
.form-actions
=f.submit pat(:save), :class => 'btn btn-primary'
=f.submit pat(:save_and_continue), :class => 'btn btn-info', :name => 'save_and_continue'
=link_to pat(:cancel), url(:posts, :index), :class => 'btn btn-default'
but i don't know what i must do in functions to save file .
An easy-to-follow guide (assuming you are using activerecord. otherwise change 1st line on example).
Add carrierwave to your Gemfile, and execute bundle install.
Generate a migration: padrino g AddImageToPosts image:string and execute it.
Add mount_uploader :image, Uploader to your Post model.
Inside your lib folder create a file, named uploader.rb (or whatever, but then do not forget to change Uploader on 3rd step.)
Add lines from 7 to 83 to uploader.rb (do not forget uncomment lines, and fix them so they to match your needs).
Browse admin, click browse button for file upload - select a file from filesystem - you are done.
example (step 3)
require 'carrierwave/orm/activerecord'
class Post < ActiveRecord::Base
belongs_to :category
mount_uploader :image, Uploader
...
end
Related
I updated to Rails4, and am now getting "wrong number of arguments (3 for 2)".
.col-md-6.col-md-offset-3
= form_for(resource, :as => resource_name, url: session_path(resource_name), :html => { :class => "search-form home-search"}) do |f|
= f.email_field :email, :id => 'beta_form', :class => 'beta_form', :placeholder => 'Email'
= f.password_field :password, :id => 'beta_form', :class => 'beta_form', :placeholder => 'Password'
= f.submit "Sign In", :class => 'btn btn-primary btn-lg btn-block beta_submit center-block'
= render "devise/shared/links"
All set. For some reason, I had to delete gem 'meta-search' after upgrading.
I'm working from the book 'Agile Web Development with Rails 4' and I'm having some difficulty with my HAML code.
I'm not too sure what I've done wrong, but my form isn't rendering when I go to build a new product. I check the source code and it's not in the HTML either so something is wrong with my code but not sure what. Hopefully someone can help me.
This is my code for Form.html.haml
=if #product.errors.any?
%div{ :id => "error_explanation" }
%h2
=pluralize(#product.errors.count, "error")
prohibited this product from being saved:
%ul
=#product.errors.full_messages.each do |msg|
%li
=msg
%div{ :class => "field" }
=f.label :title
=f.text_field :title
%div{ :class => "field" }
=f.label :description
=f.text_area :description, rows: 6
%div{ :class => "field" }
=f.label :image_url
=f.text_field :image_url
%div{ :class => "field" }
=f.label :price
=f.text_field :price
%div{ :class => "actions" }
=f.submit
And this is my New.html.haml
%h1 New Product
=render 'form'
=link_to 'Back', products_path
Thank you in advance.
According to the answers provided by meagar and theTRON as well as your last comment:
Where are you bringing to light the form object? It seems like nowhere, thus you are getting that error. When you bind a form to a model object through the form_for method, it yields a form builder object (the f variable).
Try something like the following:
<%= form_for #product, url: {action: "create"} do |f| %>
# your code using f variable ...
<% end %>
Let us know if that finally fixed your code.
Partials need to be named with an _ prefix.
Your Form.html.haml must be called _form.html.haml.
In addition to ensuring that your form is named _form.html.haml you'll need to fix some nesting in your HAML. It should look something like this instead:
=if #product.errors.any?
%div{ :id => "error_explanation" }
%h2
=pluralize(#product.errors.count, "error")
prohibited this product from being saved:
%ul
=#product.errors.full_messages.each do |msg|
%li
=msg
%div{ :class => "field" }
=f.label :title
=f.text_field :title
%div{ :class => "field" }
=f.label :description
=f.text_area :description, rows: 6
%div{ :class => "field" }
=f.label :image_url
=f.text_field :image_url
%div{ :class => "field" }
=f.label :price
=f.text_field :price
%div{ :class => "actions" }
=f.submit
Your indentation that you currently have on your form fields placed it in the scope of the if #product.errors.any? block, which means the form would only appear if #product had errors.
I have created a normal
= simple_form_for #nacform, :html => { :multipart => true } do |f|
= f.error_notification
.row
.span12
%h4 Form Details
%hr
.row
.span3
.field
= f.input :Title
.field
= f.input :Description
.field
= f.label :asset, "File"
= f.file_field :asset
.form-actions
= link_to 'Back', nacforms_path, :class => 'btn btn-small btn-primary'
%a#modal_btn.btn.btn-success.btn-small{:href => "#modal"} Continue
and the modal
#modal.modal.hide
.about
.modal-header
%button.close{"aria-hidden" => "true", "data-dismiss" => "modal", :type => "button"} ×
%h2 Forms
= simple_form_for #nacform, :html => { :multipart => true } do |f|
= f.button :submit, "Upload Form", :class => 'btn btn-success'
:javascript
$("#modal_btn").click(function(){
$('#modal').modal();
});
the submit button for the form is on the modal, but when i click on that submit button nothing happens, Am I doing it wrong ?
In order for things to appear using jQuery show method or something derived from it, you generally specify an inline style that's easy to override:
#modal.modal{ :style => 'display:none' }
Having a .hide CSS class may be what's causing it to stay hidden.
So I am using windows 7, Rails 3, latest paperclip gem and ImageMagick-6.7.7-Q16 (tested in cmd), my PATH environment is updated.
Model
class Image < ActiveRecord::Base
attr_accessible :description, :user_id, :file
has_attached_file :file, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :storage => :filesystem
belongs_to :user
#validations
validates_attachment_presence :file
validates_attachment_size :file, :less_than => 4.megabytes
validates_attachment_content_type :file, :content_type => [ 'image/gif', 'image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/jpg' ]
end
Form
<%= form_for(#image, :html => { :multipart => true }) do |image| %>
<div class="control-group">
<%= image.label :description, "Description", :class => 'control-label' %>
<div class="controls">
<div class="input-prepend">
<%= image.text_field :description %>
</div>
</div>
</div>
<div class="control-group">
<%= image.label :file, "Image", :class => 'control-label' %>
<div class="controls">
<div class="input-prepend">
<%= image.file_field :file %>
</div>
</div>
</div>
<%= image.hidden_field :user_id, :value => current_user.id %>
<div class="actions">
<%= image.submit "Upload Image", :class => 'btn btn-primary btn-medium' %>
</div>
<% end %>
My paperclip.rb in initializers
require "paperclip"
Paperclip.options[:command_path] = 'C:\Program Files (x86)\ImageMagick-6.7.7-Q16'
Paperclip.options[:swallow_stderr] = false
Paperclip.options[:whiny_thumbnails] = true
Everything is working fine without cropping (:styles => { :medium => "300x300>", :thumb => "100x100>" }). But when I want to make thumbnails Paperclip throws this error
Command :: identify -format %wx%h "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]"
Command :: convert "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]" -resize "300x300>" "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw520120519-7696-1p8rcsr"
[paperclip] An error was received while processing: #<Paperclip::Error: There was an error processing the thumbnail for DSCN630520120519-7696-18l3nw5>
Command :: identify -format %wx%h "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]"
Command :: convert "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]" -resize "100x100>" "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw520120519-7696-tx3bmo"
[paperclip] An error was received while processing: #<Paperclip::Error: There was an error processing the thumbnail for DSCN630520120519-7696-18l3nw5>
I figured out that uploaded image isn't even in temp folder, so those created images just have 0 bytes. I'm completely stuck here dunno if something wrong is with paperclip or image upload.
Any help will be appreciated
This probably means you're not pointing to IM properly. Either you don't have it installed yet or just not finding it as expected. Use double backslashes instead: 'C:\\Program Files (x86)\\ImageMagick-6.7.7-Q16'. (In order to avoid white spaces you can also use 8.3 filenames system to identify the path with regular slashes.)
If you're using the last version of Paperclip (3.1.4), on Windows I recommend you to install File package from GnuWin32. Please see this post: https://github.com/thoughtbot/paperclip/issues/926.
Finally, in order to support non-English characters in filenames, you might want to monkey patch Cocaine. I put a cocaine_path.rb between my initializers. Be aware that 'iso-8859-1' might not be the proper encoding for you.
cocaine_pacth.rb:
if RUBY_PLATFORM == "i386-mingw32"
module Cocaine
class CommandLine
def run
output = ''
begin
with_modified_path do
#logger.info("\e[32mCommand\e[0m :: #{command}") if #logger
ec = Encoding::Converter.new("utf-8", "iso-8859-1")
output = self.class.send(:'`', ec.convert(command.encode('UTF-8')))
end
rescue Errno::ENOENT
raise Cocaine::CommandNotFoundError
end
if $?.exitstatus == 127
raise Cocaine::CommandNotFoundError
end
unless #expected_outcodes.include?($?.exitstatus)
raise Cocaine::ExitStatusError, "Command '#{command}' returned #{$?.exitstatus}. Expected #{#expected_outcodes.join(", ")}"
end
output
end
end
end
end
This covers all the issues I have had with Paperclip on Windows in the last days. I hope it helps.
This is the error I am getting:
ArgumentError in Home#index
Showing /app/views/clients/_form.html.erb where line #6 raised:
You need to supply at least one validation
Extracted source (around line #6):
3: render :partial => "clients/form",
4: :locals => {:client => client}
5: -%>
6: <% client ||= Client.new
7: new_client = client.new_record? %>
8: <%= form_for(client, :html => { :class=>"ajax-form", :id => "client-ajax-form"}, :remote => true, :disable_with => (new_client ? "Adding..." : "Saving...")) do |f| %>
9: <div class="validation-error" style="display:none"></div>
My client model looks like this:
class Client < ActiveRecord::Base
# the user model for the client
belongs_to :user
has_many :projects, :order => 'created_at DESC', :dependent => :destroy
#The following produces the designers for a particular client.
#Get them from the relations where the current user is a client.
has_one :ownership, :dependent => :destroy
has_one :designer, :through => :ownership
validates :name, :presence => true,
:length => {:minimum => 1, :maximum => 128}
validates :number_of_clients
def number_of_clients
Authorization.current_user.clients.count <= Authorization.current_user.plan.num_of_clients
end
end
This is how the app/views/client/_form.html.erb partial looks:
<%#
Edit a single client
render :partial => "clients/form",
:locals => {:client => client}
-%>
<% client ||= Client.new
new_client = client.new_record? %>
<%= form_for(client, :html => { :class=>"ajax-form", :id => "client-ajax-form"}, :remote => true, :disable_with => (new_client ? "Adding..." : "Saving...")) do |f| %>
<div class="validation-error" style="display:none"></div>
<div>
<label for="client_name"><span class="icon name-icon"> </span></label>
<input type="text" class="name" size="20" name="client[name]" id="client_name" value="<%= client.name %>" > <%= f.submit(new_client ? "Add" : "Save", :class=> "green awesome")%>
</div>
<% end %>
<% content_for(:deferred_js) do %>
// From the Client Form
$('#client-ajax-form')
.bind("ajax:success", function(evt, data, status, xhr){
console.log("Calling Step View");
compv.updateStepView('client', xhr);
});
<% end %>
How do I fix that error ?
The problem is caused by the following line in your model:
validates :number_of_clients
When you use validates (s in the end) you have to follow the default rails validations like you did with the name validation. However, when you use a custom method to do the validation, you should use validate instead. So this should work:
validate :number_of_clients