Rails undefined method `user' for nil:NilClass - ruby-on-rails

Hello everyone I am new to rails and for some reason I keep getting an error
undefined method 'user' for nil:NilClass.
I have pasted an image of the error on the bottom and I posted the code below.
Image Error
# registeredapps_controller.rb
class RegisteredappsController < ApplicationController
def create
#registeredapp = Registeredapp.new(registeredapp_params)
#registeredapp.user = current_user
unless RegisteredappPolicy.new(current_user, #registeredapp).create?
flash[:alert] = "not authorized"
redirect_to user_registeredapps_path(current_user.id)
end
if #registeredapp.save
flash[:notice] = "You successfully registered your app."
redirect_to user_registeredapp_path(current_user.id, #registeredapp.id)
else
flash.now[:alert] = "There was an error registering your app. Please try again."
render :new
end
end
Policies (using Pundit Gem)
# registeredapp_policy.rb
class RegisteredappPolicy
def initialize(user, registeredapp)
#registeredapp = registeredapp
#user = user
end
def create?
if #user.present?
#user = #registerdapp.user
else
false
end
end
Here are my models
# models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
def avatar_url(size)
gravatar_id = Digest::MD5::hexdigest(self.email).downcase
"http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}"
end
has_many :registeredapps
end
# models/registeredapp.rb
class Registeredapp < ApplicationRecord
belongs_to :user
has_many :events
end

Your issue is that the instance variable #registeredapp is mispelled in the RegisteredappPolicy class under the create? method.
It currently is
def create?
if #user.present?
#user = #registerdapp.user
else
false
end
end
whereas the variable defined in the initialize is #registeredapp you're missing an e

#registerdapp is nil
#user = #registerdapp.user
use try
#user = #registerdapp.try(:user)
or
def create?
if #user.present? && #registerdapp.present?
#user = #registerdapp.user
else
false
end
end
NOTE: Also you are missing one end for if else in create? method

Rails convention usually is to have the model name like:
User
And its corresponding table name like:
users
In your ActiveRecord::Registeredapp you have :user, check if you shouldn't have :users.

Related

Getting error: undefined method `call' for nil:NilClass

I get such an error when try to create a new bound essence.
NoMethodError in AccountsController#create undefined method `call' for nil:NilClass
I have 2 bound models:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
has_one :account, dependent: :destroy
end
class Account < ApplicationRecord
belongs_to :user, optional: true
end
Account controller look like:
class AccountsController < ApplicationController
before_action :authenticate_user!
def new
#user = User.find_by(id: current_user.id)
#account = #user.build_account
end
def create
#user = User.find_by(id: current_user.id)
#account = #user.build_account(account_params)
if #account.save
flash[:success] = 'Account saved successfully'
redirect_to #account
else
render action: "new"
end
private
def account_params
params.require(:account).permit(:gender, :date_birthday, :description, :location, :nationality, :interests, :first_name, :last_name)
end
end
I tried to write #user.account.new(..), but it didn't help. I guess the error can appear because of I have an any errror in routes. But I checked it many times and found nothing.
Why do I get this error? I will be glad for your help!

Linking post to authenticated user - How do I use current_user in the controller? (devise)

I am using the Rails "Getting Started" blog post exercise, and trying to integrate with Devise for authentication and authoring of posts.
When creating an Article, the Author should be the currently logged-in user.
I am getting an error when trying to Create an Article. I know that the error is in my Articles controller, but I can't seem to figure out how to grab the current logged-in Author to kick off the creation of an Article. I believe I did the relationship properly between an Author and an Article.
Error: undefined method `articles' for nil:NilClass
Author Model:
class Author < ApplicationRecord
has_many :articles
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Articles Model:
class Article < ApplicationRecord
belongs_to :author
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
end
Articles Controller:
class ArticlesController < ApplicationController
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
#author = #current_author
#article = #author.articles.create(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
params.require(: article).permit(: title,: text,: author)
end
end
Try removing the # from #current_author. With devise, current_author is a method that returns the user by session[:user_id] not an instance variable.
Also, try doing one of three things....
Change #author.articles.create(atricle_params) to #author.articles.new(atricle_params)
Move the assignment of the author to the 'new' method as so...
def new
#article = Article.new
#article.author = current_user
end
Add a hidden_field to your form...
'<%= f.hidden_field :author_id, current_user.id %>
'

It becomes error after added associations [Ruby on Rails]

I'm having trouble with showing the articles after added has_many and belongs_to.my codes are like this.
models/blog_post.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :blog_posts, inverse_of: :user
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable
mount_uploader :image, ImageUploader
end
models/user.rb
class BlogPost < ApplicationRecord
belongs_to :user, inverse_of: :blog_posts
end
controllers/blog_posts_controller.rb
class BlogPostsController < ApplicationController
before_action :authenticate_user!
def new
#bp = BlogPost.new
end
def create
#bp = BlogPost.new
#bp.user_name = current_user
#bp.title = params[:blog_post][:title]
#bp.content = params[:blog_post][:content]
#bp.save
redirect_to blog_post_path(#bp.id)
end
def show
#bp = BlogPost.find(params[:id])
end
def destroy
#bp = BlogPost.find(params[:id])
#bp.destroy
redirect_to root_path(#bp)
end
end
views/blog_posts/new.html.slim
h1 Let's post your article!
= form_for #bp do |f|
h2 title
= f.text_field :title
h2 content
= f.text_area :content
br
= f.submit "Submit"
a href="/" Home
views/blog_posts/show.html.slim
h2 name
p = #user.user_name
h2 title
p = #bp.title
h2 content
p = #bp.content
a href="/"Home
and I get this error...
ActionController::UrlGenerationError in BlogPostsController#create``No route matches {:action=>"show", :controller=>"blog_posts", :id=>nil} missing required keys: [:id]
Is there any idea of solving this problem?
seems like the BlogPost is not saved and that's why its redirecting it with id = nil
Try changing the code to
if #bp.save
redirect_to blog_post_path(#bp.id)
else
render :edit
end
Try to redirect to your newly created object #bp, you don't really require the blog_post_path(#bp.id)
The following should also work fine
def create
#bp = BlogPost.new
#bp.user_name = current_user
#bp.title = params[:blog_post][:title]
#bp.content = params[:blog_post][:content]
respond_to do |format|
if #bp.save
redirect_to #bp, notice: 'Blog Post was successfully created.'
else
render :edit
end
end
end
However, it might also be that your routes are not correctly set, if the above is not working, please share your config/routes.rb file to see how is it defined.
you can also define it like this in your file
config/routes.rb
resources :blog_posts

Create function not recognized on user

I have the following classes in my model:
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
has_one :list
end
and
class List < ActiveRecord::Base
belongs_to :user
end
Now I want to create a new list button on my list/show page where I can create a new list for a current_user.
def new
#list = List.new
end
def create
#list = current_user.list.build(params.require(:list).permit(:title))
if #list.save
redirect_to #list, notice: "List was saved successfully."
else
flash[:error] = "Error creating list. Please try again."
render :new
end
end
But something goes wrong in my create function. I makes sense cause also when I open rails c and try:
u = User.first => validated user
u = List.new
I get the error that list is not method for u (my user). What goes wrong?
You didn't provide information about error, but I guess interpreter complains about calling build method on nil. It's because you call:
#list = current_user.list.build(params.require(:list).permit(:title))
but current_user.list returns nil. You should have this instead:
#list = current_user.build_list(params.require(:list).permit(:title))
Documentation for has_one method

Create another model upon Devise User registration

I'm trying to create a Profile model upon my Users registering for the site. As I have it now the Profile model is being created upon registration with the correct foreign key. My problem lies with trying to update the Profile model after the user has gone through the Devise confirmation steps.
My users are called "artists".
### /artists/registrations_controller.rb ###
class Artists::RegistrationsController < Devise::RegistrationsController
# GET /resource/sign_up
def new
super
#profile = #artist.build_artist_profile
end
# POST /resource
def create
super
#profile = #artist.create_artist_profile(profile_params)
end
private
def profile_params
params.permit(:biography, :location, :genre, :members, :facebook_url, :twitter_url, :youtube_url, :itunes_url, :amazon_url)
end
end
### /artists/profiles_controller ###
class Artists::ProfilesController < ApplicationController
before_action :authenticate_artist!
before_action :correct_artist
before_action :set_artist
def edit
#profile = ArtistProfile.find_by(params[:artist_id])
end
def update
#profile = ArtistProfile.find_by(params[:artist_id])
if #profile.update_attributes(profile_params)
redirect_to current_artist
else
redirect_to root_url
end
end
private
def set_artist
#artist = current_artist
end
def correct_artist
#artist = current_artist
if #artist != Artist.find(params[:id])
redirect_to artist_path
end
end
def profile_params
params.require(:artist_profile).permit(:biography, :location, :genre, :members, :facebook_url, :twitter_url, :youtube_url, :itunes_url, :amazon_url)
end
end
### /artist.rb ###
class Artist < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable
has_one :artist_profile, dependent: :destroy
### /artist_profile.rb ###
class ArtistProfile < ActiveRecord::Base
belongs_to :artist
validates :artist_id, presence: true
end
I put my own code into the Devise registration controller in the create method. Upon registration the ArtistProfile model is created and populated with blank strings, which is prefect. However, if I try to edit/update the individual artist's profile only the very first artist's profile gets updated.
ie. Artist 1 signs up and profile 2 is created. Artist 1 updates Profiles 1's location to Buffalo via the edit page. Artist 2 signs up and Profile 2 is created. Artist 2 updates Profile 2's location to New York, but Profile 1's location is updated, not Profile 2's.
Is this the way to create a model upon registration, and if so, how do I fix the edit/update methods?
Or is there a better way altogether?
This line of your code is incorrect:
#profile = ArtistProfile.find_by(params[:artist_id])
A fix is to find the artist, then get the profile:
#profile = Artist.find(params[:artist_id]).artist_profile
An optimization:
#artist = Artist.find(params[:artist_id]).includes(:artist_profile)
#profile = #artist.artist_profile
Or, if your controller is receiving the artist profile id, then you can do this fix:
#profile = ArtistProfile.find(params[:artist_profile_id])

Resources