syntax error, unexpected keyword_end - ruby-on-rails-4

ever since i updated to rails 4 i've been struggeling with strong_params. I finaly tought i had it but now there seems to an unexpected_end some where. i think i overlook everything but it still seems to be wrong somewhere.
i'm very new to ruby on rails aswel.
user.rb
class User < ActiveRecord::Base
#attr_accessible :name, :email, :password, :password_confirmation
#attr_acessor :password
has_secure_password
before_save { self.email = email.downcase }
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :nickname, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:uniqueness => { :case_sensitive => false },
:format => { :with => email_regex }
validates :password, :presence => true,
end
users_controller.rb
class UsersController < ApplicationController
def new
#title = "Sign Up"
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
redirect_to #user
else
render "new"
end
end
private
def user_params
params.require(:user).permit(:nickname, :email, :password, :password_confirmation )
end
end

As per the comment, i.e., i forgot the comma at the end validates :password, :presence => true, OP has resolved the issue. I am just posting it as an answer (not expecting credit for the same) so SO community knows that the question is complete and answered.
You have an extra comma at the end of validates :password, :presence => true, which is causing the error.
Removing that would resolve your issue.
validates :password, :presence => true

Related

How to configure Rails 5, paperclip 5, aws-sdk 2 on heroku properly?

I deployed Rails 5 app local with paperclip attachments: all was working fine. Only on heroku I need AWS s3 and it does not work with Rails 5.0.1/paperclip 5.1.0/aws-sdk 2.7.3.
Has anybody a working configuration for storing attachments on s3?
This is my models/article.rb:
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
has_attached_file :attachment,
:url => ":s3_domain_url",
#:path => ':filename',
:storage => :s3,
:bucket => ENV['AWS_BUCKET'],
:s3_bucket => ENV['AWS_BUCKET'],
:s3_permissions => :private,
:s3_protocol => 'http',
:s3_host_name => 's3.amazonaws.com',
#:s3_host_alias => 's3.amazonaws.com',
:s3_region => ENV['AWS_REGION'],
#:region => ENV['AWS_REGION'],
:s3_credentials => { :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_KEY_ID'],
:endpoint => 's3.amazonaws.com' }
# Explicitly do not validate
do_not_validate_attachment_file_type :attachment
#validates_attachment :attachment, content_type: { content_type: 'application/x-java-archive'}, size: { in: 0..10.megabytes }
end
The environment variables are set to:
AWS_ACCESS_KEY_ID=....
AWS_BUCKET=....
AWS_REGION=us-east-1
AWS_SECRET_KEY_ID=....
The articles_controller is:
class ArticlesController < ApplicationController
http_basic_authenticate_with name: "gerrit", password: "_tVo1I44iyLe", except: [:index, :show]
def index
#articles = Article.all
end
def show
#article = Article.find(params[:id])
end
def new
#article = Article.new
end
def edit
#article = Article.find(params[:id])
end
def create
#article = Article.new(article_params)
if #article.save
redirect_to #article
else
render 'new'
end
end
def update
#article = Article.find(params[:id])
if #article.update(article_params)
redirect_to #article
else
render 'edit'
end
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to articles_path
end
private
def article_params
#article_params =
params.require(:article).permit(:title, :text, :attachment)
##article.update_attributes( article_params )
end
end
This is the error I have now locally and on heroku, next to many others before:
uninitialized constant Paperclip::Storage::S3::AWS
Extracted source (around line #26):
#article = Article.new(article_params)
if #article.save #line 26
redirect_to #article
else
render 'new'
Parameters:
{"utf8"=>"✓", "authenticity_token"=>"snGgVwA5tqQTPHXwXW1Fx/lmLMS1bL+94jF68KQh031gpX2N78gOK45hCP8w71ObFo6moHQuJXxNnUW0bCUeVw==",
"article"=>
{"title"=>"test1",
"text"=>"",
"attachment"=>
#<ActionDispatch::Http::UploadedFile:0x007f46c00881e0
#content_type="application/x-desktop",
#headers="Content-Disposition: form-data; name=\"article[attachment]\"; filename=\"Antichamber.desktop\"\r\n" + "Content-Type: application/x-desktop\r\n",
#original_filename="Antichamber.desktop",
#tempfile=#<File:/tmp/RackMultipart20170306-5350-esbhtd.desktop>>},
"commit"=>"Create Article"}
For convenience I add the URL to the broken Rails 5 app here:
gmr-heroku
Everything is working fine now!
NB: You want me to pose different questions and not adding to the original question. Now you don't want duplicate answers.
:url => :s3_domain_url should be :url => ":s3_domain_url"

Routing Error Using Rails Favorites, Polymorphic

Following a tutorial for adding favorites to my existing project, whereby users can favorite property listings but can't get past the error below:
Routing error,uninitialized constant FavoriteRoomsController
favoriterooms_controller.rb
class FavoriteRoomsController < ApplicationController
before_action :set_room
def create
if Favorite.create(favorited: #room, user: current_user)
redirect_to #room, notice: 'Room has been favorited'
else
redirect_to #room, alert: 'Something went wrong...*sad panda*'
end
end
def destroy
Favorite.where(favorited_id: #room.id, user_id: current_user.id).first.destroy
redirect_to #room, notice: 'Room is no longer in favorites'
end
private
def set_room
#room = Room.find(params[:room_id] || params[:id])
end
end
room.rb
class Room < ActiveRecord::Base
belongs_to :user
has_many :photos
has_many :favorites
geocoded_by :address
after_validation :geocode, if: :address_changed?
validates :home_type, presence: true
validates :room_type, presence: true
validates :accommodate, presence: true
validates :bed_room, presence: true
validates :bath_room, presence: true
validates :listing_name, presence: true, length: {maximum: 50}
validates :summary, presence: true, length: {maximum: 500}
validates :address, presence: true
validates :lister_type, presence: true
validates :gender_type, presence: true
validates :occupation_type, presence: true
validates :move_in, presence: true
validates :term, presence: true
validates :term, presence: true
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :omniauthable
validates :fullname, presence: true, length: {maximum: 50}
has_many :rooms
has_many :favorites
has_many :favorite_rooms, through: :favorites, source: :favorited, source_type: 'Room'
def self.from_omniauth(auth)
user = User.where(email: auth.info.email).first
if user
return user
else
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.fullname = auth.info.name
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.image = auth.info.image
user.password = Devise.friendly_token[0,20]
end
end
end
end
favorite.rb
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :favorited, polymorphic: true
end
routes.rb
Rails.application.routes.draw do
root 'pages#home'
devise_for :users,
:path => '',
:path_names => {:sign_in => 'login', :sign_out => 'logout', :edit => 'profile'},
:controllers => {:omniauth_callbacks => 'omniauth_callbacks',
:registrations => 'registrations'
}
resources :users, only: [:show]
resources :rooms
resources :photos
resources :conversations, only: [:index, :create] do
resources :messages, only: [:index, :create]
end
resources :favorite_rooms, only: [:create, :destroy]
end
roomshow.html.erb
favorites button link code added in my roomsshow.html.erb
<%- unless current_user.favorite_rooms.exists?(id: #room.id) -%>
<%= link_to 'Add to favorites', favorite_rooms_path(room_id: #room), method: :post %>
<%- else -%>
<%= link_to 'Remove from favorites', favorite_room_path(#room), method: :delete %>
<%- end -%>
favorite_rooms_path POST /favorite_rooms(.:format) favorite_rooms#create
favorite_room_path DELETE /favorite_rooms/:id(.:format) favorite_rooms
Screenshot of error message with full trace
I've watched various tututorials and followed numerous suggestions but dont seem to be able to solve the issue by myself.
Routing error,uninitialized constant FavoriteRoomsController
Rails follow naming conventions very strictly and for a good reason. It expects the file names to be in a snake case. So you should change the file name favoriterooms_controller.rb to favorite_rooms_controller.rb

Getting "Unpermitted parameters" error for deivse

Hi am working on sample app where I am using devise for authentication.
I am adding following extra parameters while registration.
:first_name, :last_name, :mobile, :gender, :address
But I am getting following Unpermitted parameters: first_name, last_name, password_confirmation error while registering new user.
I refereed following links
Add Custom Field/Column to Devise with Rails 4
http://www.jacopretorius.net/2014/03/adding-custom-fields-to-your-devise-user-model-in-rails-4.html
But it didn't worked. Here is not code set
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_confirmation_of :password, :only => :create
end
I also implemented same in application controller but it didn't worked so I created separate
registration controller.
registration_controller.rb
class RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:first_name, :last_name, :mobile, :gender, :address, :email, :password, :password_confirmation)
end
devise_parameter_sanitizer.for(:account_update) do |u|
u.permit(:name,
:email, :password, :password_confirmation, :current_password)
end
end
end
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
def after_sign_in_path_for(resource)
user_landing_page
end
def user_landing_page
contact_us_path
end
end
devise/registration/new.html.haml
.container
.row
.col-sm-6.col-md-4.col-md-offset-4
%h1.text-center.login-title Create New Account
.account-wall
%img.profile-img{:alt => "", :src => "https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"}
= form_for(resource, as: resource_name, class: "form-signin input-medium", url: session_path(resource_name)) do |f|
= f.text_field :first_name, class: "form-control", placeholder: "First Name", autofocus: true
= f.text_field :last_name, class: "form-control", placeholder: "Last Name", autofocus: true
= f.email_field :email, class: "form-control", placeholder: "Email", autofocus: true
= f.password_field :password, class: "form-control", placeholder: "Password", autocomplete: "off"
= f.password_field :password_confirmation, class: "form-control", placeholder: "Confirm Password", autocomplete: "off"
= f.submit "Log in", class: "btn btn-lg btn-primary btn-block login-button"
development.log
Parameters: {"utf8"=>"✓", "authenticity_token"=>"pe7wBW3iWnn39p3nJAi8utbuECj+x8zX/pIxr/6sKbo=", "user"=>{"first_name"=>"first_name", "last_name"=>"last_name", "email"=>"admin#my.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Log in"}
Unpermitted parameters: first_name, last_name, password_confirmation
Rendered devise/sessions/new.html.haml within layouts/application (6.6ms)
Rendered layouts/_home_header.html.haml (1.2ms)
Completed 200 OK in 426ms (Views: 316.8ms | ActiveRecord: 0.0ms)
routes.rb
Rails.application.routes.draw do
root :to => 'landing#index'
devise_for :users, :controllers => {:registrations => "registrations"}
get '/about_us' => 'statics#about_us', as: :about_us
get '/contact_us' => 'statics#contact_us', as: :contact_us
end
can any one suggest what I am missing.
I am using Rails 4.1.4, ruby 2.1.2 and devise 3.4.1.
As per my understanding, you are registering new user. Here is your mistake
= form_for(resource, as: resource_name, class: "form-signin input-medium", url: session_path(resource_name)) do |f|
you are using session_path that means you are going to "Log In" not for "Sign Up". So change it
= form_for(resource, as: resource_name, class: "form-signin input-medium", url: registration_path(resource_name)) do |f|

Rails 4 Paperclip with Devise, file saving error

I'm using devise gem with paperclip to handle authentication and upload pictures. Problem is that I have used paperclip on the same model twice for storing two pictures (let's call those paperclip columns :avatar , :superbadge), my model name is User.
Now, when I choose to upload two pictures, my rails application ignores the first file that I have chosen, instead It uses second chosen file and saves it in the first paperclip column, leaving second paperclip column blank. How do I fix it?
My application controller:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_devise_permitted_parameters, if: :devise_controller?
protected
def configure_devise_permitted_parameters
registration_params = [:name, :email, :password, :password_confirmation,:avatar,:superstarbadge]
if params[:action] == "update"
devise_parameter_sanitizer.for(:account_update) {
|u| u.permit(registration_params << :current_password)
}
elsif params[:action] == "create"
devise_parameter_sanitizer.for(:sign_up) {
|u| u.permit(registration_params)
}
end
end
end
My User.rb model:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :validatable
has_attached_file :avatar, :styles => { :small => "100x100>" }
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
has_attached_file :superstarbadge, :styles => { :tiny => "100x100>" }, :default => "superbadge.jpg"
validates_attachment_content_type :superstarbadge, :content_type => /\Aimage\/.*\Z/
has_many :questions
has_many :answers
def to_s
email
end
end
My form_for for creating new user with devise gem (I'm using slim template language not erb):
h1 Sign up
= form_for(resource, as: resource_name, url: registration_path(resource_name), :html => { :multipart => true }) do |f|
= devise_error_messages!
.field
label= f.label :name
= f.text_field :name, autofocus: true
.field
label= f.label :email
= f.email_field :email, autofocus: true
.field
label= f.label :password
= f.password_field :password, autocomplete: 'off'
.field
label= f.label :password_confirmation
= f.password_field :password_confirmation, autocomplete: 'off'
.field
= f.label :avatar
= f.file_field :avatar
.field
= f.file_field :avatar
div
= f.submit "Sign up"
Both the file_field's in your form are referring to avatar field so when you submit the form the second chosen file (i.e., latest) gets saved as avatar. There is no file_field for superstarbadge so it never gets saved.
You need one file_field for avatar and other one for superstarbadge. So, your code should look like:
.field
= f.label :avatar
= f.file_field :avatar
.field
= f.file_field :superstarbadge ## This one should be superstarbadge and NOT avatar

Devise email and password can not be blank

I have this code in my application_controller.rb
before_filter :update_sanitized_params, if: :devise_controller?
before_filter :store_location
protect_from_forgery with: :exception
def update_sanitized_params
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :password_confirmation, :role)}
devise_parameter_sanitizer.for(:sign_in) {|u| u.permit(:email, :password) }
end
but I still have validation errors from devise
Email can't be blank
Password can't be blank
Password can't be blank
Role is not included in the list
Devise was working fine few days ago I don't know what messed up with it I have added active_admin may be this created conflicts any help please??
Assuming that you are getting the validation errors while updating a User record.
def update_sanitized_params
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :password_confirmation, :role)}
devise_parameter_sanitizer.for(:sign_in) {|u| u.permit(:email, :password) }
## Permit the attributes for account_update
devise_parameter_sanitizer.for(:account_update) {|u| u.permit(:email, :password, :password_confirmation, :role) }
end
You need to permit the attributes explicitly which you would like to be updated by specifying devise_parameter_sanitizer.for(:account_update) else they would not be passed to users table for updating.
I have solved the Problem by adding this line in user.rb
attr_accessible :email, :password, :role
and this works with gem " protected_attributes"