Form not saving if try to upload image with Paperclip - ruby

so paperclip, seems as if there is a different way to get it working every time i use it.
So at the moment i try and submit a form but it fails and re renders the form (which is what its supposed to do if the form does not save).
This is my setup so far
Gemfile
gem "paperclip", "~> 3.0"
Controller
def new
#post = Post.new
end
def create
#user = current_user
#post = #user.posts.new(params[:post])
if #post.save
redirect_to root_path, :notice => 'Post Successfully Created'
else
render :action => 'new'
end
end
Post Model
class Post < ActiveRecord::Base
belongs_to :category
belongs_to :user
attr_accessible :comments, :title, :category_id, :user_id, :photo
has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
Form
<%= form_for #post, :class => 'post-form', :html => { :multipart => true } do |f| %>
<%= f.label :title, "Title", :class => 'title_label' %>
<%= f.text_field :title %>
<%= f.label :category_id, "Choose Category", :class => 'title_label' %>
<%= f.collection_select(:category_id, Category.all, :id, :name, :prompt => "Please Select a Category") %>
<%= f.label :comments, "Comments", :class => 'title_label' %>
<%= f.text_area :comments %><br>
<%= f.file_field :photo %>
<%= f.submit 'Submit', :class => 'btn' %>
<% end %>
My migration to add photo was successful as my schema looks like so
create_table "posts", :force => true do |t|
t.string "title"
t.text "comments"
t.integer "category_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
end
Can anyone see reason why this is not working as expected?
EDIT
Do i need ImageMagick installed to allow the upload of an image or is this just for rendering an image in the view?
ok so from the comments i have started to try and debug and put this in my view
<%= #post.errors.full_messages %>
I get this returned
["Photo C:/Users/RICHAR~1/AppData/Local/Temp/bitman20130724-5600-agvtgn.png is not recognized by the 'identify' command.", "Photo C:/Users/RICHAR~1/AppData/Local/Temp/bitman20130724-5600-agvtgn.png is not recognized by the 'identify' command."]
Any ideas?
Thanks

Step 1
From paperclip documentation:
ImageMagick must be installed and Paperclip must have access to it. To ensure that it does, on your command line, run which convert (one of the ImageMagick utilities). This will give you the path where that utility is installed. For example, it might return /usr/local/bin/convert.
Then, in your environment config file, let Paperclip know to look there by adding that directory to its path.
In development mode, you might add this line to config/environments/development.rb:
Paperclip.options[:command_path] = "/usr/local/bin/"
Step 2
For agvtgn.png is not recognized by the 'identify' command. error:
Not sure how you do this in windows, for linux this is what you need to do:
$ which identify
/path/to/identify
Set command_path to that path in config/environments/development.rb:
Paperclip.options[:command_path] = "/path/to"
also you need ImageMagick to be installed
http://ganeshprasadsr.blogspot.com/2010/12/paperclip-issue-is-not-recognized-by.html
What I think - You just need to install ImageMagick.
p.s. Windows is the worst development machine. You could install at least a virtual machine running on linux.

Related

Multi model sign up with clearance in Rails 4

So I want to create a Company while signing up as a new user to my application. I use https://github.com/thoughtbot/clearance for authentication.
I have these 2 migrations:
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :name, null: false
t.string :email, null: false
t.attachment :logo
t.timestamps null: false
end
end
end
And
class CreateClearanceUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email, null: false
t.string :encrypted_password, limit: 128, null: false
t.string :confirmation_token, limit: 128
t.string :remember_token, limit: 128, null: false
t.string :first_name
t.string :last_name
t.attachment :avatar
t.integer :company_id
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :remember_token
end
end
My models look like this:
class User < ActiveRecord::Base
include Clearance::User
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users
end
This is my altered Clearance controller:
class Clearance::UsersController < ApplicationController
before_filter :redirect_signed_in_users, only: [:create, :new]
skip_before_filter :require_login, only: [:create, :new]
skip_before_filter :authorize, only: [:create, :new]
def new
#user = User.new
#user.build_company
render template: "users/new"
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
redirect_back_or url_after_create
else
render template: "users/new"
end
end
private
def avoid_sign_in
warn "[DEPRECATION] Clearance's `avoid_sign_in` before_filter is " +
"deprecated. Use `redirect_signed_in_users` instead. " +
"Be sure to update any instances of `skip_before_filter :avoid_sign_in`" +
" or `skip_before_action :avoid_sign_in` as well"
redirect_signed_in_users
end
def redirect_signed_in_users
if signed_in?
redirect_to Clearance.configuration.redirect_url
end
end
def url_after_create
Clearance.configuration.redirect_url
end
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, companies_attributes: [:id, :name])
end
end
And at last my form:
<div class="form-item">
<%= form.label :first_name %>
<%= form.text_field :first_name, type: "text" %>
</div>
<div class="form-item">
<%= form.label :last_name %>
<%= form.text_field :last_name, type: "text" %>
</div>
<div class="form-item">
<%= form.label :email %>
<%= form.text_field :email, type: "email" %>
</div>
<div class="form-item">
<%= form.fields_for :companies do |builder| %>
<label>Company</label>
<%= builder.text_field :name, type: "text" %>
<%end%>
</div>
<div class="form-item">
<%= form.label :password %>
<%= form.password_field :password %>
</div>
I can perfectly submit my form, but my company_id is nil when finding the user object in rails console.
Anyone have an idea what I am doing wrong?
Thanks in advance!
You need to use the singular:
= form.fields_for :company
and in your controller:
company_attributes # instead of companies_attributes
and you have one thing in the wrong model! You want to save a company with the user so you need to move accepts_nested_attributes_for to user.rb
accepts_nested_attributes_for :company

How can I solve MassAssignmentSecurity error using rails version 3.2.19

Can anybody please help me to resolve the following error using rails version-3.2.19 ?When i am submitting values to database this error is coming.
Error
ActiveModel::MassAssignmentSecurity::Error in UsersController#create
Can't mass-assign protected attributes: con_password
My code snippets are as follows.
views/users/new.html.erb
<center>
<h1>Enter your data</h1>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-div">
<%= form_for :user,:url => {:action => 'create'} do |f|%>
<p>
<%= f.label :Name %>
<%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
<%= f.label :Email %>
<%= f.email_field :email,placeholder:"Enter your Email" %>
</p>
<p>
<%= f.label :Password %>
<%= f.password_field :password,placeholder:"Enter your password" %>
</p>
<p>
<%= f.label :password %>
<%= f.password_field :con_password,placeholder:"Enter your password again" %>
</p>
<p>
<%= f.label :content %>
<%= f.text_field :content,placeholder:"Enter your content" %>
</p>
<p>
<%= f.submit "Create User",:class => 'submit' %>
</p>
<% end %>
</div>
</center>
controller/users_controller.rb
class UsersController < ApplicationController
def index
end
def new
#user=User.new
end
def show
end
def create
#user=User.new(params[:user])
if #user.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="User could not create"
flash[:color]="invalid"
render :new
end
end
end
model/user.rb
class User < ActiveRecord::Base
attr_accessible :content, :email, :name, :password
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
end
migrate\20150128062543_create_users.rb
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :password
t.string :content
t.timestamps
end
end
end
Please help me to solve this issue.
Instead of <%= f.password_field :con_password,placeholder:"Enter your password again" %>, you should name your field password_confirmation, because this is what your model expects if it has validates :password, confirmation: true:
<%= f.password_field :password_confirmation, placeholder: "Enter your password again" %>
You also have to add password_confirmation to attr_accessible in the model.

How to list the users who LIKE a given Post

I am having trouble figuring out how to list all of the USERS who have LIKED a particular POST. Currently I am using:
<span class="count"><%= dailypost.likes.count %></span>
This has allowed me to count all of the LIKES associated with that particular POST.BUT it does not list the actual users.
I have tried using this to list all of the USERS who LIKED that POST
<%= dailypost.likes %>
Instead I get back:
[#<Like id: 360, dailypost_id: 306, user_id: 1, created_at: "2013-04-28 21:51:45", updated_at: "2013-04-28 21:51:45">,
#<Like id: 319, dailypost_id: 306, user_id: 104, created_at: "2013-04-28 19:27:35", updated_at: "2013-04-28 19:27:35">,
#<Like id: 314, dailypost_id: 306, user_id: 103, created_at: "2013-04-28 19:24:19", updated_at: "2013-04-28 19:24:19">]
DOES ANYONE KNOW HOW I CAN PULL THE LIST OF USERS OR USER_ID'S??
New to RAILS please help!!
MODELS
class User < ActiveRecord::Base
has_many :likes, dependent: :destroy
has_many :dailyposts, dependent: :destroy
end
class Dailypost < ActiveRecord::Base
belongs_to :user
has_many :likes
end
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :dailypost
end
DATABASE
ActiveRecord::Schema.define(:version => 20130210095553) do
create_table "dailyposts", :force => true do |t|
t.string "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "likes", :force => true do |t|
t.integer "dailypost_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
VIEWS
<span class="count"><%= dailypost.likes.count %></span>
<%= dailypost.likes %>
<span class="like">
<% if like = current_user.likes.find_by_dailypost_id(dailypost.id) %>
<%= form_for like, :html => { :method => :delete }, remote: true do |f| %>
<span title="Unlike!"><%= image_submit_tag "Superman1.png" %></span>
<% end %>
<% else %>
<%= form_for current_user.likes.build, remote: true do |f| %>
<div><%= f.hidden_field :dailypost_id, value: dailypost.id %></div>
<%= f.hidden_field :user_id %>
<span title="Like!"><%= image_submit_tag "Superman2.png" %></span>
<% end %>
<% end %>
</span>
The simplest way to understand is to take each like, and ask it for its user:
dailypost.likes.map {|l| l.user}
Of course that does a database lookup for each like, which you may wish to avoid if you have hundreds and hundreds of users.
So a more sophisticated way is to do a single query to get all the users by user_id:
User.find(dailypost.likes.map {|l| l.user_id})
This will give you a list of users, and it's up to you what you do with it. If you just want a HTML list, try this instead:
<ul>
<% dailypost.likes.each do |l| %>
<li> <%= link_to(l.user.name, l.user) %></li>
<% end %>
</ul>
This looks at each like in turn, and then asks it for its user, and then asks the user for its name.

Several polymorphic associations using class_name?

I am trying to create an article which holds in_prices and out_prices (one for each country) using rails polymorphic associations and nested forms.
I have a data model which looks something like this:
# app/models/article.rb
class Article < ActiveRecord::Base
has_many :out_prices, :class_name => "Price", :as => :priceable
has_many :in_prices, :class_name => "Price", :as => :priceable
end
# app/models/price.rb
class Price < ActiveRecord::Base
belongs_to :priceable, :polymorphic => true
end
# db.schema for prices
create_table "prices", :force => true do |t|
t.integer "value"
t.integer "country_id"
t.integer "priceable_id"
t.string "priceable_type"
end
The article and its associations are created using a nested form like:
# app/views/articles/_article_form.html.erb
<%= form_for setup_article(#article) do |f| %>
<%= f.fields_for :in_prices do |ff| %>
<%= ff.text_field :value %>
<% end %>
<%= f.fields_for :out_prices do |ff| %>
<%= ff.text_field :value %>
<% end %>
<% end %>
The setup_article method is a helper method to build the associations:
# app/helpers/articles_helper.rb
def setup_article(article)
if article.in_prices.nil?
# Setup one in price for each country
Country.all.each do |country|
article.in_prices.build(:value => 0, :country_id => country.id)
end
end
if article.out_prices.nil?
# Setup one out price for each country
Country.all.each do |country|
article.out_prices.build(:value => 0, :country_id => country.id)
end
end
article
end
setup_article is needed to make sure empty price form fields (one for each country) shows up when creating a new article.
Now to the actual problem. When I edit an already created Article (which have associated in_prices and out_prices) Rails won't be able to differentiate between these different types of polymorphic associations (in_prices and out_prices). Because of this both nested form helpers renderes form fields for all associated prices, which isn't the desired behavior. I only want to list in_prices in the one of the nested forms, and the out_prices in the other.
How should these associations be configured to make sure rails can differentiate between the in_prices and out_prices associations in the two different nested form helpers?
EDIT (SOLVED)
A friend of mine pointed out I need to add yet another field in the prices table to flag what type of price it is. I called this field price_type and the db.schema ended up looking like this:
# db.schema for prices
create_table "prices", :force => true do |t|
t.integer "value"
t.integer "price_type"
t.integer "country_id"
t.integer "priceable_id"
t.string "priceable_type"
end
Note: Don't name this field 'type' since this is a reserved name.
The 'price_type' field can be populated either by adding a hidden field in the nested forms (less safe), or to handle it in the controller before saving the article and its associated data. I chose to add it as hidden params like:
# app/views/articles/_article_form.html.erb
<%= form_for setup_article(#article) do |f| %>
<%= f.fields_for :in_prices do |ff| %>
<%= ff.text_field :value %>
<%= ff.text_field :price_type, :value => "in" %>
<% end %>
<%= f.fields_for :out_prices do |ff| %>
<%= ff.text_field :value %>
<%= ff.text_field :price_type, :value => "out" %>
<% end %>
<% end %>
To make sure the associations gets filtered correctly they need to be declared with the ':conditions' tag, like:
# app/models/article.rb
class Article < ActiveRecord::Base
has_many :out_prices, :class_name => "Price", :as => :priceable, :conditions => { :price_type => "in" }
has_many :in_prices, :class_name => "Price", :as => :priceable, :conditions => { :price_type => "out" }
end
.. and now everything works as expected. cheers!

Using ClientSideValidations gem inside ajax rendered partial

I am currently using the ClientSideValidations gem and stuck while rendering a partial using ajax and trying to validate addresses inside that rendered partial with the gem mentioned above. Nothing happens when entering a wrong combination specified in the model.
If browsing to the address-form directly and trying out validations, everything works fine, just like specified.
Any hints or thoughts on how to make the validations gonna work inside the partial?
Thanks!
EDIT: No errors in JS console, just nothing happens when for example entering a too short zipcode (specified in the model with 5 digits). Btw I use haml for the views.
So the code in my view:
= link_to "Shipping", addresses_path, :remote => true
corresponding controller addresses_controller.rb
respond_to do |format|
...
format.js {render :layout => false}
...
end
corresponding index.js.erb
$("#ajax_content").html("<%= escape_javascript(render :partial =>
"partialXY") %>");
and corresponding partial
= form_for #address, :validate => true, :id => "address_form", :remote => true do |f|
- if #address.errors.any?
#error_explanation
%h2
= pluralize(#address.errors.count, "error")
prohibited this user from being saved:
%ul
- #address.errors.full_messages.each do |msg|
%li
=msg
%ul
%li
= f.label :type
= f.select :address_type, [['Billing Address', 'billing'],['Shipping Address',
'shipping']], :class => "address_selection"
%li
= f.label :gender
= f.select :gender, [['Male', 'male'],['Female', 'female']], :class => "text_field"
%li
= f.label :last_name
= f.text_field :last_name, :id => "last_name", :class => "text_field"
%li
= f.label :first_name
= f.text_field :first_name, :class => "text_field"
%li
= f.label :company_name
= f.text_field :company_name, :class => "text_field"
%li
= f.label :street
= f.text_field :street, :class => "text_field"
%li
= f.label :number
= f.text_field :number, :class => "text_field"
%li
= f.label :zipcode
= f.text_field :zipcode, :class => "text_field"
%li
= f.label :place
= f.text_field :place, :class => "text_field"
%li
= f.label :phone_no
= f.text_field :phone_no, :class => "text_field"
%li
= f.label :country
= f.text_field :country, :class => "text_field"
%li
= f.label :email
= f.text_field :email, :class => "text_field"
%li
= f.submit
so like I said nothing happens when validating the rendered partial inputs like zipcode, etc. The funny thing is, that if you look at the following, automatically by rails generated view for editing addresses, the validation works just fine.
rails generated view to edit address
=render 'partialXY'
I have been working on this issue for a long time and have absolutely no clue on how to fix this. I'm sure it has something to do with ajax since using validation when rendering the rails generated partial works just fine.
Thanks a lot! Phil
Ok I fixed it. Turned out despite giving the form an ID, the ID was a different one in the final html code. So I just added a
$('form.form_real_id').validate();
to my .js.erb file!

Resources