I have the following model:
class Coupon < ActiveRecord::Base
belongs_to :company
validates :description, presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false }
validates :fine_print, presence: true
end
and the following method in the coupon controller:
def redeem
if params[:pin] == #coupon.company.pin
redirect_to root_path
else
flash.now[:notice] = "Incorrect Pin"
render :show
end
end
This form is in the a view:
<%= form_for( #coupon, :url => coupons_redeem_path( #coupon ), :html => { :method => :post } ) do |f| %>
<%= label_tag("pin", "Search for:") %>
<%= text_field_tag("pin") %>
<%= f.submit "Close Message" %>
<% end %>
I want the form to call the redeem method in the coupons controller when hitting submit but am getting this error:
No route matches [POST] "/coupons/redeem.1"
EDIT
These are my routes:
resources :companies do
resources :coupons
end
get 'coupons/redeem'
In your routes, coupons are nested resources of companies. So you should choose one of these alternatives:
1st:
resources :companies do
resources :coupons do
post :redeem, on: :member
end
end
This leads to helpers like this: redeem_company_coupon_path(company, coupon) (and send smth there via POST).
If you don't want to include company to your path, you could choose 2nd:
resources :companies do
resources :coupons
end
post 'coupons/:id/redeem', to: 'coupons#redeem', as: :redeem_coupon
After that you could use redeem_coupon_path(coupon) helper
Related
I'm trying to allow users to sign in with either their username or their email address.
as per here: https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address
When ever I try to sign in with either the email or the login this is logged:
Started POST "/users/sign_in" for 192.168.2.8 at 2013-11-22 10:11:50 +0800
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"WVTOKWQ8yJAJSu3NmXi3skJ8UC8zXY7qGZj7qbM3cr0=", "user"=>{"email"=>"testuser", "password"=>"password"}, "commit"=>"Sign in"}
User Load (3.3ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'testuser' ORDER BY "users"."id" ASC LIMIT 1
Completed 401 Unauthorized in 20ms
Processing by Devise::SessionsController#new as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"WVTOKWQ8yJAJSu3NmXi3skJ8UC8zXY7qGZj7qbM3cr0=", "user"=>{"email"=>"rtype", "password"=>"password"}, "commit"=>"Sign in"}
Rendered devise/sessions/new.html.erb within layouts/application (6.4ms)
Completed 200 OK in 80ms (Views: 62.6ms | ActiveRecord: 0.0ms)
its weird the sql isn't checking for the username, so maybe the call on the user is wrong, but its exactly from the devise documentation.
I have read the following:
Adding Username to devise rails 4
Logging in with username using Devise with Rails 4
I also reviewed the warden code and the devise code to try and discover if I'm overriding the wrong method in the user.
Any ideas why it is not authenticating with username, when it does with email?
ApplicationController.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :password, :remember_me) }
# Need to add other user fields like gender etc.
devise_parameter_sanitizer.for(:account_update) {|u| u.permit(:email, :password, :password_confirmation, :current_password)}
end
end
User.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable, :encryptable, :recoverable, :rememberable, :trackable, :validatable
attr_accessor :login # This is used to add the login for allowing user to sign in with both email or username
# Validations
validates :username, presence: true, length: {maximum: 255}, uniqueness: { case_sensitive: false }, format: { with: /\A[a-zA-Z0-9]*\z/, message: "may only contain letters and numbers." }
# Overwrite devise’s find_for_database_authentication method in user model
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:username)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions).first
end
end
end
new.html
<fieldset>
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => { :class => 'form-horizontal' }) do |f| %>
<div class="control-group">
<%= f.label :login, "Email or Username" %>
<div class="controls"><%= f.text_field :login, :autofocus => true %></div>
</div>
<div class="control-group">
<%= f.label :password %>
<div class="controls"><%= f.password_field :password %></div>
</div>
<div class="form-actions">
<%= f.submit "Sign in", :class => "btn btn-primary", data: { disable_with: 'Working...' } %> <%= link_to "Forgot password?", new_password_path(resource_name), :class => "btn" %>
</div>
<% end %>
</fieldset>
Devise.rb
config.secret_key = 'Omitted for security'
config.mailer_sender = 'Omitted for security'
config.case_insensitive_keys = [ :email ]
config.strip_whitespace_keys = [ :email ]
config.skip_session_storage = [:http_auth]
config.stretches = Rails.env.test? ? 1 : 10
config.reconfirmable = true
config.password_length = 8..128
config.reset_password_within = 6.hours
config.encryptor = :sha512
config.sign_out_via = :delete
You need to add
config.authentication_keys = [ :login ]
within devise.rb
Also if you want to use login as reset password or confirmation keys you should also add within the same file:
config.reset_password_keys = [ :login ]
config.confirmation_keys = [ :login ]
You also need to whitelist the login parameter within your application_controller. In the new.html view you have a login form, so you must accept the login parameter for the sign_in instead of the username and email parameters.
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :password, :remember_me) }
I'm going through the rails tutorial and my login page is throwing an exception after exercise 8.1.5 when I click the login button with no email or pw entered:
http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec-rendering_with_a_flash_message
Error:
NoMethodError in SessionsController#create
undefined method `[]' for nil:NilClass
app/controllers/sessions_controller.rb:7:in `create'
SessionsController matches the final code exactly for the Create method
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email].downcase) #line 7
if user && User.authenticate(params[:session][:password])
#will fill this in later
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
end
end
I did change the button label to Log in instead of "Sign in" as that is too confusing with "Sign up", but I didn't think that would create the problem. sessions\new.html.erb
<% provide(:title, "Log in") %>
<h1>Log in</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(:sesssion, url: sessions_path) do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "Log in", class: "btn btn-large btn-primary" %>
<% end %>
<p>New user? <%= link_to "Sign up now!", signup_path %></p>
</div>
</div>
This post hints that I need a method in my user model, but adding that didn't help:
NoMethodError in SessionsController#create
I tried adding this to user.rb, but it didn't help
results from find_by_email executed in function differs from console:
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return user.nil? ? nil : user
end
Any ideas would be greatly appreciated!
I've looked at the example from the book and your code and I noticed this line
if user && User.authenticate(params[:session][:password])
your User.authenticate should be lowercased to user.authenticate. Revert back to your original code.
I have just had the same problem and found that in fact i needed [:sessions] with an s on the end!
So line reads
if user && User.authenticate(params[:sessions][:password])
Hope this helps someone in the future!
I had the same problem after doing exercise 1 in chapter 8 where I replaced the use of form_for with form_tag. This resulted in the name attributes in the generated input form fields changing from name="session[email]" and name="session[password]" to name="email" and name="password". Subsequently, I needed to access the params using params[:email] and params[:password] instead of params[:session][:email] and params[:session][:password].
My new Sessions controller looks like this:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email].downcase)
if user && user.authenticate(params[:password])
sign_in user
redirect_to user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
sign_out
redirect_to root_url
end
end
This solved the problem for me. Hope this is helpful to someone else.
In this section from the tutorial chapter 8, all instances of [:session] should be [:sessions]. Hope that helps.
class SessionsController < ApplicationController
.
.
.
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
.
.
.
end
Could you confirm the word 'session' in app/view/session/new.html.erb spelling correct?
I see you wrote:
form_for(:sesssion, url: sessions_path) do |f|
But in app/controllers/sessions_controller.rb, you wrote:
user = User.find_by_email(params[:session][:email].downcase) #line 7
They must be the same.
I am new to rails, I was working on paperclip gem and wanted to save the simple files, saved from paperclip.
I have the My model as follow :-
class UserAttachment < ActiveRecord::Base
attr_accessible :email, :user_id, :attached_file
has_attached_file :attached_file
validates_attachment_presence :attached_file
validates_attachment_size :attached_file, :less_than => 20.megabytes
end
My controller action where the form is called :-
class HomeController < ApplicationController
def index
#uattachment = UserAttachment.new
end
end
Index view code, where the form is located
<%= form_for #uattachment, :url => attachment_get_link_path, :html => { :method => :post, :id => 'attachment_form', :multipart => true }, :remote => true do |f| %>
<%= f.email_field :email, :value=>nil, :placeholder => "Enter your email here", :required => true %><br />
<%= f.file_field :attached_file %>
<%= f.submit "Submit" %>
<% end %>
I want to use some following kind of code to save the data :-
(Code below is not the correct code, it's an excitation to tell what I want to do in my application.)
#uattachment = UserAttachment.new
#uattachment = params[:user_attachment]
#uattachment.save
Params received are as follows :-
(rdb:6) pp params
{"utf8"=>"✓",
"authenticity_token"=>"dfjaskldjadslgjsoidruts48589034lsker=",
"user_attachment"=>
{"email"=>"testing#email.com",
"attached_file"=>
#<ActionDispatch::Http::UploadedFile:0x007fcb58682ba0
#content_type="image/jpeg",
#headers=
"Content-Disposition: form-data; name=\"user_attachment[attached_file]\"; filename=\"someimage.jpg\"\r\nContent-Type: image/jpeg\r\n",
#original_filename="800px-Kinnaur_Kailash.jpg",
#tempfile=#<File:/tmp/RackMultipart20121205-8432-1fc1kpi>>},
"commit"=>"Submit",
"controller"=>"attachment",
"action"=>"get_link"}
Got the catch, it was pretty simple, I checked it from the scaffolded assignment,
def index
#uattachment = UserAttachment.new(params[:user_attachment])
#uattachment.save
end
And you get the golden words in response "true".
I'm trying to do something that seems conceptually simple, but I just can't get it working. Here's what I'm trying to do:
I have a simple "search" form on the /users/index page. It
leverages jQuery Tokeninput to autocomplete a user (name/username)
when the current user types into the search field. What I want to do
is let the user type a name, select a user from the list, then click
"submit" and be taken to the selected user's profile (/users/:id/ - which is
Users#show). I have jQuery Tokeinput configured to submit the user_id as :user_token.
I can't seem to get this working. The autocomplete part works correctly, but I can't figure out how to "submit" so that the entered user's profile is shown.
Here's what happens when I hit the "submit" button on the form (pulled from the development log in the terminal):
Started PUT "/users/2" for 127.0.0.1 at 2012-05-08 11:19:56 -0400
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"blah blah=", "user"=>{"user_token"=>"41"}, "commit"=>"Go to profile", "id"=>"2"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "2"]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1
Completed 500 Internal Server Error in 83ms
NoMethodError (undefined method `downcase!' for nil:NilClass):
app/controllers/users_controller.rb:119:in `update'
So it's calling the update action on the users controller, I assume because "#user" already exists (specifically, it's the current_user who clicks the submit button).
On screen, I see:
The path shown up top is .../users/2 (the id of current user), and in
the browser I see:
NoMethodError in UsersController#update
undefined method `downcase!' for nil:NilClass
I'm getting that because it's trying to run the "update" action in the Users controller, and there's a "downcase!" call on one of the params at the beginning up the update action. That parameter ([:user][:email]) obviously doesn't exist since it's not in the form I'm submitting.
What I really want to do is go to "/users/41" (the show page for the user whose id is passed as params[:user][:user_token]). How do I do this?
Here's all the relevant code:
#users_controller.rb#Index
def index
#title = "All users"
#label = "All users"
#list_users = User.order(:name).page(params[:page]) #generates users shown on index page
#user = current_user
# This is used to populate the autocomplete field in the little search form
#users = User.where("LOWER(name) like ? OR LOWER(username) like ?", "%#{params[:q].downcase}%", "%#{params[:q].downcase}%").order('name ASC').limit(10) if params[:q]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users, :only => [:id, :name, :username] }
end
end
My routes...
#routes.rb
resources :comments
resources :invitations
resources :sessions, :only => [:new, :create, :destroy]
resources :shares, :controller => "item_shares", :as => "item_shares" do
resources :comments
end
resources :posts, :controller => "item_posts", :as => "item_posts" do
resources :comments
end
resources :items
resources :relationships, only: [:create, :destroy]
resources :users do
member do
get :following, :followers
end
end
resources :password_resets
match '/signup', :to => 'users#new'
match '/signup/:invitation_token' => 'users#new', :as => :signup_with_invitation
match '/signin', :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'
match '/invite', :to => 'invitations#new'
match '/users/:id/shared', :to => 'users#shared'
match '/users/:id/received', :to => 'users#received'
match '/users/:id/saved', :to => 'users#saved'
match '/users/:id/posts', :to => 'users#posts'
match '/reciprocal_followers', :to => 'users#reciprocal_followers'
root :to => 'pages#home'
Here is my form (this definitely does NOT work, although the jQuery Tokeninput does work):
#_user_search_form.html.erb
<div class="form">
<span class="form-label-right round-bottom-left-5 round-top-right-5 gray-gradient">Find someone</span>
<%= form_for #user, :action => "show" do |f| %>
<div class="field">
<%= f.label :user_token, "Name or Username" %></br>
<%= f.text_field :user_token, :placeholder => 'John Doe or JohnDoe123', "data-pre" => (#pre_populate_data.to_json(:only => [:id, :name, :username]) unless #pre_populate_data.nil?) %>
</div>
<div class="actions">
<%= f.submit "Go to profile" %>
</div>
<% end %>
</div>
Here's the relevant part of my user model:
#user.rb
attr_accessible :user_token
attr_reader :user_token
<% form_for #project, :url => { :controller => "project", :action => "thumbnail_save" } do |form| %>
....
<% end %>
Also write something like this in your config file (put it at the top)
get "users/show"
If that doesn't work try this. (you might have to change your form for below to work)
match "project/thumbnail_save", :to => "project#thumbnail_save"
Let us know if any more issues.
I can't debug why I am getting an error:
class VendorsController < ApplicationController
def tag_cloud
#tags = Vendor.tag_counts_on(:tags)
end
I set this class as Taggable:
class Vendor < ActiveRecord::Base
acts_as_taggable_on :tags, :competitors
I include the TagsHelper:
module VendorsHelper
include TagsHelper
end
This is in my View:
<% tag_cloud(#tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
<%= link_to tag.name, { :action => :tag, :id => tag.name }, :class => css_class %>
<% end %>
This is the error that I get:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?
Each instance of Vendor has at least one Tag.
Got it, I needed to add: #tags = Vendor.tag_counts_on(:tags) in the index controller.