I am building an application in which I am trying to login using clearance.I have build login and sign up page .They are working very smooth but the problem is when I am trying to show error when user enters any wrong email or password so my <% if :session.errors.any? %> is not working .It is saying undefined method `errors' for :session:Symbol
[Session_controller]
class SessionController < ApplicationController
def new
end
def create
#session = authenticate(params)
sign_in(#session) do |status|
if status.success?
redirect_to root_path
else
render 'new'
end
end
end
private
def user_params
params.require(:session).permit(:email,:password)
end
end
[session/_form.html.erb]
You are calling errors on :session, which is a symbol.
You may want to try calling errors on #session.
undefined method `errors' for :session:Symbol
errors should be called on a new model instance i.e, Model.new. You should have #session defined as Session.new in new method, the below should work
#session_controller
def new
#session = Session.new
end
#in the view
<% if #session.errors.any? %>
Related
I am trying to create a destination, but it keeps telling me in my browser that 'name' is nil when it redirects redirects to my 'show' view.
Error I receive
undefined method `name' for nil:NilClass
Here are my controller actions for new, create, and show:
def show
#destination = Destination.find_by(id: params[:id])
end
def new
#destination = Destination.new
end
def create
#destination = Destination.create(dest_params)
redirect_to user_destination_path(current_user, #destination.id )
end
private
def dest_params
params.require(:destination).permit(:name,:user_id)
end
My new form where I enter the name of the destination:
<h2>Add a destination</h2>
<div>
<%= form_for #destination do |f|%>
<%= f.label :name %>
<%= f.text_field :name %><br>
<%= f.submit %>
<% end %>
</div>
here is my read/show view:
<h3>Added destination</h3>
<div>
<p><%= #destination.name %></p>
</div>
Before all this I was getting missing required keys [:id] errors, but I seemed to fix that but for some reason I suspect that might have something to do with the issue I am having now. Let me know if you are able to spot the issue
Updated Error
No route matches {:action=>"show", :controller=>"destinations", :id=>nil, :user_id=>"1"}, missing required keys: [:id]
The main problem here is a total lack of error handling. You're not checking at all if the user provided valid input or if the record was even saved in your create method.
def create
#destination = Destination.create(dest_params)
redirect_to user_destination_path(current_user, #destination.id )
end
If the record is not saved for example due to a failed validation #destination.id is nil.
In your show method you're using find_by instead of find which just lets the error slide instead of raising a ActiveRecord::RecordNotFound error.
Your controller should actually look like:
class DestinationsController
def show
# will raise if the record is not found and return a 404 not found response
# instead of just exploding
#destination = Destination.find(params[:id])
end
def new
#destination = Destination.new
end
def create
# never just assume that the record is created unless you want
# to get kicked in the pants.
#destination = Destination.new(dest_params)
if #destination.save
# this route really does not need to be nested.
# see https://guides.rubyonrails.org/routing.html#shallow-nesting
redirect_to user_destination_path(current_user, #destination)
else
# re-render the form with errors
render :new
end
end
private
def dest_params
params.require(:destination).permit(:name,:user_id)
end
end
Rails 5.2
In my inventories_controller.rb, I have the following:
before_action :fetch_product, only: [:show]
def show
........
end
def fetch_product
if params.has_key?(:sku)
#product = Product.get_product(params)
end
end
This works fine, when I do: http://0.0.0.0:3000/sku/12345678
I am trying to implement search functionality, so I modified nventories_controller.rb as follows:
def fetch_product
if params.has_key?(:search) && !params[:search].blank?
product = Product.find_by_sku(params[:search])
if !product
params = params.except[:search]
redirect_to product_show_path, alert: 'Product was not found'
end
params = params.merge!(:sku, product.sku)
end
if params.has_key?(:sku)
#product = Product.get_product(params)
end
end
When I do: http://0.0.0.0:3000/sku/12345678
I get an instant error message:
undefined method `has_key?' for nil:NilClass
Using my debugger, I find that on entry into the fetch_product method, params is nil
Any idea what's going on?
params = params.merge!(:sku, product.sku) modifies the hash in place and returns nil, don't do that assignment, just call params.merge! (if you still want to do the assignment, remove the "!").
Personally, I wouldn't modify the params hash unless it's really really needed, I would use another variable.
Every time I submit the form I get this error: undefined method `each' for nil:NilClass. If everything is correct I can submit the form without any problems, but when there is one thing missing it gives me that error. The error sends me to this line:
views/users/new.html.haml
- #subscriptions.each do |fbs|
= fb.radio_button :subscription_id, fbs.id, class: 'radiobtn', required: true
controllers/users_controller.rb
def new
#user = Users::Business.new
#subscriptions = Businesses::Subscription.all
end
def create
#user = Users::Business.new(user_params)
if #user.save
sign_in(#user)
else
render :new
end
end
Assigns subscriptions in a create action too:
before_filter :set_subscriptions, only: %w(new create) #for edit and update if needed
private
def set_subscriptions
#subscriptions = Businesses::Subscription.all
end
Or add #subscriptions = Businesses::Subscription.all directly to create action after the saving is failed and you re-render new form.
It is happening because there is no value persisted with that model .
You can check the data into the rails console
like ,
$rails console
> Businesses::Subscription.count
And if you see that there is no data then you can write a if ... end block to check for null value and handle it.
I have in my orders/edit.html.erb a form that begins like this:
<%= simple_form_for [#reservation, #order] do |f| %>
Orders Controller:
def edit
#reservation = Reservation.find_by_id(params[:reservation_id])
#order = Order.find_by_id(params[:id])
end
Association:
Reservation :has_one Order
Routes:
resources :reservations do
resources :orders
end
If my path resembles something like /reservations/10/orders/10/edit I end up getting an error from Rails saying NoMethodError in Orders#edit and undefined method 'model_name' for nil:NilClass
When I create a new order the form works perfectly fine so not sure why i'm getting an error all of a sudden, can someone help me with this issue?
Current implementation is prone to failure when the URL supplied either a reservation ID or an order ID that is not valid. Two ways to handle this:
First, let Rails do it for you:
def edit
#reservation = Reservation.find(params[:reservation_id])
#order = Order.find(params[:id])
end
This will raise an ActiveRecord::RecordNotFound error, which, in production, should lead users to your 404 page.
If you'd prefer to keep find_by_id and handle this manually, or to rescue from this error in a different way, you can do:
def edit
#reservation = Reservation.find_by_id(params[:reservation_id])
#order = Order.find_by_id(params[:id])
if #reservation.nil? || #order.nil?
raise ActiveRecord::RecordNotFound.new # Or, do something else
end
end
That would yield the same result as above ... just more code.
I'm getting
undefined method `errors' for nil:NilClass
When I made my custom validation before create new data table.
This is my code in the the controller, everything works fine before the validation method trigger.
class ActivitiesController < ApplicationController
layout 'admin'
before_action :admin_logged_in_user, only: [:create, :destroy,:edit,:update]
before_action :admin_correct_user, only:[:destroy,:update,:edit]
before_action :permanent_event_check, only:[:create,:update]
def list
end
def create
#activity = admin_current_user.activities.build(activity_param)
if #activity.save
flash[:success] = "Activity Created!"
redirect_to admin_dashboard_url
else
render 'new'
end
end
def new
#activity = Activity.new
end
private
def activity_param
params.require(:activity).permit(:name,:details,:start_at,:end_at,
:activity_image01_url,:activity_image02_url,:activity_image03_url,
:youtube_url,:capacity,:booking_status,:rules,:apply_details,
:payment_price,:payment_need,:avaliable,:rating,:temple_id)
end
def admin_correct_user
#activity = admin_current_user.activities.find_by(id: params[:id])
redirect_to admin_dashboard_url if #activity.nil?
end
def permanent_event_check
param_activity = params[:activity]
if param_activity[:permanent] == "false"
if param_activity[:start_at] == "" || param_activity[:end_at] == ""
#activity.errors[:base] << "You can't leave start and end date blank with Permanent Event"
return false
end
end
end
end
And this line.
#activity.errors[:base] << "You can't leave start and end date blank with Permanent Event"
I got the error from this line.
How to fix this?
Thanks!
******* add model file after moving validation
This is my model after i tried to move my validation but it seems like nothing in return from #activity
validate :permanent_event_check
private
def permanent_event_check
param_activity = #activity
if param_activity.permanent == "false"
if param_activity.start_at == "" || param_activity.end_at == ""
#activity.errors[:base] << "You can't leave start and end date blank with Permanent Event"
return false
end
end
end
From your before_action blocks:
before_action :admin_logged_in_user, only: [:create, :destroy,:edit,:update]
before_action :admin_correct_user, only:[:destroy,:update,:edit]
before_action :permanent_event_check, only:[:create,:update]
You have the admin_correct_user which is setting #activity before you have permanent_event_check from where you are adding the error.
However, admin_correct_user only triggers for the actions: [:destroy,:update,:edit] while permanent_event_check triggers for create and update.
The Implication of this is that for the create action, the order of events in your controller is: admin_logged_in_user (which is probably a validation) -> permanent_event_check (trying to add errors). Notice that the other action (admin_correct_user) which was meant to set #activity was skipped.
Therefore... for the create action especially, as at the point where you are trying to add the error, there is no object named #activity.
#activity is Nil
So... the reason for the error.
To fix it:
Ensure to build the #activity object before trying to access it(for validation or for any other thing).
Arup's suggestion of moving the validation into your model is a great one!
To Move it to the model:
#activity.rb:
validate :right_event
def right_event
#check validity, and add custom error here
unless permanent
errors.add(:permanent, "You can't leave start and end date blank...") unless self.start_at and self.end_at
end
end