Paperclip "Gem" Rails 3.1 undefined method model file name - ruby-on-rails-3.1

Using rails 3.1.1, Ruby 1.9.2,
Gems: gem 'haml', gem 'simple_form', gem 'aws-sdk',
gem 'paperclip', :git => "git://github.com/thoughtbot/paperclip.git"
plugin: country_select: git://github.com/rails/country_select.git
Having an issue uploading/displaying images pushed to Amazon S3 through paperclip (GEM)
Error: undefined method `avatar_file_name' for #Player:0x00000102aff228
For the most part I was following the example on the git-hub page for paperclip
https://github.com/thoughtbot/paperclip
Here is what I have in my code:
Migration: 20111224044508_create_players.rb
class CreatePlayers < ActiveRecord::Migration
def change
create_table :players do |t|
t.string :first_name
t.boolean :first_name_public, :default => false
...
t.string :website
t.boolean :website_public, :default => false
t.has_attached_file :avatar
t.timestamps
end
end
end
Model: Player.rb:
class Player < ActiveRecord::Base
attr_accessible :first_name, ... :website
validates_presence_of :username, :email
has_attached_file :avatar,
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => ":class/:id/:style/:filename"
{Unrelated validations}
end
S3 file: s3.yml
development:
bucket: voh_development
access_key_id: *********************
secret_access_key: ********************
staging:
bucket: voh_staging
access_key_id: *********************
secret_access_key: ********************
production:
bucket: voh_production
access_key_id: *********************
secret_access_key: ********************
Controller: players_controller.rb
class PlayersController < ApplicationController
def create
#player = Player.create(params[:player])
if #player.save
redirect_to players_path, :notice => "Player Created";
else
render :action => 'new'
end
end
{basic restful}
end
Views:
Edit.html.haml + New.html.haml
= simple_form_for #player do |f|
= f.input :first_name
...
= f.input :website
= f..file_field :avatar
.input_div
= f.button :submit
index.html.haml
...
%td Avatar
%td First Name
...
%td Actions
- #players.each do |player|
%tr
%td
= image_tag #player.avatar.url(:thumb)
%td
= player.first_name
...
%td
= link_to ' Show ', player_path(player.id)
|
= link_to ' Edit ', edit_player_path(player.id)
show.html.haml
= image_tag #user.avatar.url
%br
= #player.first_name
...
Research:
I found a lot to do with the pluging and genration of the migration but it all seems old. Most of them suggest putting in the up down in the migration for the 4 attributes. However it seems that should have been replaced by the one line t.has_attached_file :avatar.
I have a rails 3.0 project and this worked. I am able to upload products and pull them back down. (had to play with the suggested image_tag #icon.avatar.url and turned it into %img{:src => URI.unescape(icon.icon.url)} but that a different question.)

TLDR: Fixed typo in index.html.haml from #player => player, Added :avatar to attr_accessible.
I woke up this morning and had a different error.
instead of: undefined method Avatar_file_name'
I got: undefined method avatar' for nil:NilClass
That error was caused buy a simple type in my code. I used an instance vairable instead of .each variable I should have been using (index.html.haml:9)
Now the app was not erring out but the file was still not uploading.
In the development log I found this. (I did not look here the first time I posted)
WARNING: Can't mass-assign protected attributes: avatar
I then went and added :Avatar to attr_accessible and everything started working.
Not sure if this is supposed to be required or not but I did see that they had updated S3 header to be a proc yesterday.
https://github.com/thoughtbot/paperclip/tree/master/test/storage
I am not going to close this out yet. There will be an edit because I am going to play with the version and quickly report my findings today. Then I will close this out.
Edit:
I tryed switch back to 2.4.5 and I am getting the error that made me switch to pulling master in the first place. When attempting to do a migration with t.has_attached_file :avatar it fails to migrate and gives the following error.
undefined method `has_attached_file' for #ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition:0x00000105053600
I think I will stick with pulling from master.

Related

Download link on Paperclip Attachment in Rails_admin

I am using rails_admin gem together with Paperclip. My model looks like this:
class Product < ActiveRecord::Base
has_attached_file :asset,
:styles => {
:thumb => "100x100#",
:small => "150x150>",
:medium => "200x200" }
validates_attachment_content_type :asset, :content_type => /\Aimage\/.*\Z/
end
How can I include a download link into the index action? So that, on admin/products every entry in the table will have a download link? I read through the documentation, but they don't seem to specify any of these features.
[EDIT]
On my main index action which was routed here: /products I used to do:
<%= link_to "Download", product.asset.url(:original, false) %>
You just need to do.
<%= link_to "Download", product.asset(:original) %>
or
<%= link_to "Download", product.asset.url(:original) %>
They both do the same thing.
If you want to change what version of the image they download just change :original to :medium, :small or :thumb.
For Rails Admin do following:
config.model "Product" do
list do
....
field :download do
formatted_value do
bindings[:view].tag(:a, href: bindings[:object].assets(:original)) << "Download"
end
end
end
...
end
[SOLVED]
Submission model:
class Submission < ActiveRecord::Base
# Image attachment and validations
has_attached_file :file,
:url => "/files/:class/:attachment/:id/:style/:basename.:extension",
:path => ":rails_root/public/files/:class/:attachment/:id/:style/:basename.:extension"
validates_attachment_content_type :file, :content_type => 'application/pdf'
end

Add a record in Many to many relation fails

I have a many to many connection in Rails applications, it looks like this:
class Workspace
has_and_belongs_to_many :users, dependent: :destroy
end
class User
has_and_belongs_to_many :workspaces
end
class UserWorkspace
belongs_to :user
belongs_to :workspace
end
Schema:
create_table :users_workspaces do |t|
t.integer :user_id
t.integer :workspace_id
t.integer :role, default: 0
t.timestamps null: false
end
Then I want to create a new record like this:
#user.workspaces.create(:workspace_id => #workspace.id, :role => 1)
or this
#user.workspaces << #workspace
and have an error in logs:
(0.0ms) begin transaction
(0.0ms) begin transaction
(0.1ms) rollback transaction
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 207ms (ActiveRecord: 5.5ms)
Completed 500 Internal Server Error in 207ms (ActiveRecord: 5.5ms)
ActiveRecord::UnknownAttributeError (unknown attribute 'workspace_id' for Workspace.):
app/controllers/sessions_controller.rb:10:in `block in sign_up'
app/controllers/sessions_controller.rb:4:in `sign_up'
What am I doing wrong?
PS Controller:
def sign_up
respond_to do |format|
#user = User.new(user_params)
if #user.save
#workspace = Workspace.new(title: "#{#user.name}'s workspace")
#workspace.save
puts "workspace id: #{#workspace.id}"
#user.workspaces.create(:workspace_id => #workspace.id, :role => 1)
puts "workspaces count: #{#user.workspaces.count}"
#user.workspace = #workspace
#user.update_attributes(user_params)
flash.now[:success] = 'Welcome! Please check activation letter in your email box.'
format.js { render 'signup_message' }
else
format.js { render 'render_signup_errors' }
end
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :name, :workspace_id)
end
There are couple of problems with your code. For example, you are creating workspaces that are already created (#user.workspaces.create), or permitting a :workspace_id that is not used, etc.
Pleas see code below:
def sign_up
respond_to do |format|
#user = User.new(user_params)
if #user.save
#workspace = Workspace.new(title: "#{#user.name}'s workspace")
if #workspace.save
# Like this
UserWorkspace.create(user: #user, workspace: #workspace, role: 1)
# Or, like this
#user.user_workspaces.create!(workspace_id: #workspace.id, role: 1)
end
flash.now[:success] = 'Welcome! Please check activation letter in your email box.'
format.js { render 'signup_message' }
else
format.js { render 'render_signup_errors' }
end
end
end
private
# You don't need :workspace_id since you are not using it anywhere
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :name)
end

How to resolve Errno::ECONNREFUSED in UsersController#create error in ROR

Can anybody help me to resolve this following error.I am trying to send an email but it failed to send and throws some error.
Error:
Errno::ECONNREFUSED in UsersController#create
No connection could be made because the target machine actively refused it. - connect(2)
app/controllers/users_controller.rb:8:in `create'
My code snippets are given below.
views/users/index.html.erb
<h1>Send email to your friend</h1>
<%= form_for #user,:url => {:action => 'create'} do |f| %>
<%= f.text_field:name,placeholder:"Enter your name" %><br>
<%= f.email_field:email,placeholder:"Enter your email" %><br>
<%= f.submit "Send" %>
<% end %>
views/users/new.html.erb
<h1>Successfully registered</h1>
views/users/success.html.erb
<h1>Email sent successfully</h1>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#user=User.new
end
def create
#user=User.new(users_params)
if #user.save
UserMailer.registration_confirmation(#user).deliver
redirect_to :action => 'success'
else
render :'index'
end
end
def new
end
def success
end
private
def users_params
params.require(:user).permit(:name, :email)
end
end
views/user_mailer/registration_confirmation.text.erb
<%= #user.name%>
<h1>Thank you for registering</h1>
Click <%= link_to "here",users_new_path %>
mailer/user_mailer.rb
class UserMailer < ApplicationMailer
default :from => "w5call.w5rtc#gmail.com"
def registration_confirmation(user)
#user=user
mail(:to => user.email, :subject => "Registered")
end
end
config/initializers/setup_mail.rb
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "w5call.w5rtc#gmail.com",
:password => "w5rtc123#",
:authentication => "plain",
:enable_starttls_auto => true
}
endActionMailer::Base.default_url_options[:host] = "localhost:3000"
development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.action_mailer.delivery_method = :smtp
end
routes.rb
Rails.application.routes.draw do
root 'users#index'
post "users/create" => "users#create"
get "users/success" => "users#success"
get "users/new" => "users#new"
end
Actually i was referring this tutorial.I am using rails-4 and ruby 1.9.3.Please help me to resolve this error.

Testing custom routes in rails 3.0.1 does not work, or is it me?

For some reason when I run this functional test
require 'test_helper'
class ListControllerTest < ActionController::TestCase
test "should get mylist" do
post :mylist, :format => :json
assert_response :success
end
end
routes.rb
SomeApplication::Application.routes.draw do
match "/mylist" => "list#mylist", :method => "POST"
end
list_controller.rb
class ListController < ApplicationController
def mylist
respond_to do |format|
format.json { render :json => []}
end
end
end
Sourcecode as a gist
I get this error:
1) Error:
test_should_get_mylist(ListControllerTest):
ActionController::RoutingError: No route matches {:controller=>"list", :format=>:json, :action=>"mylist"}
/test/functional/list_controller_test.rb:6:in `test_should_get_mylist'
Any ideas?
Regards,
Michal
OK. I got it. Those stupid errors are the most difficult to spot. Sometimes I cry for ruby to have strong typing ;)
the problem is in the routes.rb. Instead of:
match "/mylist" => "list#mylist", :method => "POST"
it should have been
match "/mylist" => "list#mylist", :via => :post
Thanks everyone who tried to help me.

Two-page sign-up process in rails?

I'm attempting to create a rails app where a user will sign up, then immediately be directed to fill out a profile with more detailed information.
I'm currently attempting this by having both a users and a profile model, with a has_one/belongs_to relationship between the two models.
I'm having trouble with createing the profile for the user. Tests fail with undefined methodprofiles' for #when testing the creation, and using an automated profile builder calledsample_data.rake`:
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
admin = User.create!(:name => "name name",
:email => "fakename#fake.com",
:password => "password",
:password_confirmation => "password")
admin.toggle!(:admin)
99.times do |n|
name = Faker::Name.name
email = Faker::Internet.email
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
User.all.each do |user|
User.profiles.create(:city => Faker::Address.city,
:state => Faker::Address.us_state_abbr,
...
)
end
end
end
Also fails on
I'm having trouble with createing the profile for the user. Tests fail with undefined method 'profiles'
profiles_controller.rb is:
class ProfilesController < ApplicationController
before_filter :authenticate, :only => [:create, :edit]
def create
#profile = current_user.profiles.build(params[:profile])
if #profile.save
flash[:success] = "Profile Created!"
redirect_to root_path
else
render 'pages/home'
end
end
def edit
end
end
profile.rb is
class Profile < ActiveRecord::Base
attr_accessible :city, :state, ...
belongs_to :user
validates :city, :presence => true
validates :state, :presence => true
...
end
Can anyone see what I'm doing wrong? Is there a way to merge all the items I need under "users", validate the presence of all the required information, and have the signup process be two pages?
Other suggestions for this?
Why do you do this?
1.times do...end
You dont need that.
The failure comes up because you need to create ONE profile, not profiles, for one certain user.
So try this:
User.all.each do |user|
user.create_profile(:city => "bla", ...)
end
In you controller the same. You have just one profile, using singular will help out.

Resources