Is my project class is nill or what, can any one explain me this error.
NoMethodError (undefined method projects' for nil:NilClass):
app/controllers/project_controller.rb:8:inindex'
Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_source.erb
(6.2ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.4ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
(1.0ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb
within rescues/layout (50.0ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb
(0.4ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb
within layouts/inlined_string (0.3ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb
within layouts/inlined_string (0.3ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb
within layouts/inlined_string (0.4ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (41.3ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb
within layouts/javascript (0.3ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.4ms) Rendered
/Users/ajaysithagari/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (93.4ms)
Here is my project controller
before_action :confirm_logged_in
before_action :find_company
def index
#projects = #company.projects.sorted
end
def show
#project = Project.find(params[:id])
end
def new
#project = Project.new()
end
def create
#project = Project.new(project_params)
if #project.save
redirect_to(:action => 'index')
else
render('new')
end
end
def edit
#project = Project.find(params[:id])
end
def update
#project = Project.find(params[:id])
if #project.update_attributes(project_params)
redirect_to(:action => 'index')
else
render('new')
end
end
def delete
#project = Project.find(params[:id])
end
def destory
#project = Project.find(params[:id])
#project.destroy
redirect_to(:action => 'index')
end
private
def project_params
params.require(:project).permit(:name, :position, :type_of_project, :description, :no_of_tasks)
end
def find_company
if params[:company_id]
#company = Company.find(params[:company_id])
end
end
end
So actually what iam doing here is before entering in to projects we need to find the company_id and in index #projects = #company.projects.sorted means that company has many projects.
The problem is with the if params in the def find_company. For the index function this is not set.
change def index to:
def index
#projects = Project.sorted
end
UPDATE: made an error I think:
def index
#projects = Project.all.sorted #or leave the call to sorted out completely
end
Related
I tried to learn about presenter and did the following classes
User model with id, first_name, last_name, email
user_controller with the following methods
def index
#users = User.all
render_user_json #users
end
def show
#user = User.find_by_id(params[:id])
if #user.nil?
render json: { message: 'User can not be found' }, status: 404
return
end
render_user_json #user
end
def render_user_json(user)
render json: ::Presenters::User::UserPresenter.new(user).generate
end
UserPresenter class
module Presenters
module User
class UserPresenter
attr_reader :user
def initialize(user)
#user = user
end
def generate
{
id: #user.id,
first_name: #user.first_name,
last_name: #user.last_name,
email: #user.email
}
end
end
end
end
When I go to localhost:3000/users/id it works well
but when I go to localhost:3000/users I get the following error
NoMethodError (undefined method `id' for #<User::ActiveRecord_Relation:0x00007f9952ac4930>
Did you mean? ids):
lib/presenters/user/user_presenter.rb:14:in `generate'
app/controllers/users_controller.rb:49:in `render_user_json'
app/controllers/users_controller.rb:9:in `index'
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/actionpack-4.2.11/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.0ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/actionpack-4.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/actionpack-4.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/actionpack-4.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (108.3ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.4ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.4ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (91.6ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.7ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.8ms)
Rendered /Users/noammansur/.rvm/gems/ruby-2.3.8/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (210.6ms)
It seems like it doesn't passed as single users
Rather than this:
render_user_json #users
Either make another method render_users_json (note the plural users) or just call the render from the index method directly like this:
# inside index method
render json: users.map do |user|
::Presenters::User::UserPresenter.new(user).generate
end
I am trying to implement the functionality of creating a new article. However when I click the Submit button it gives me the following error.
Started POST "/articles" for 127.0.0.1 at 2017-12-23 14:04:29 +0500
Processing by ArticlesController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lbrD/8QZAlLuxVbw3vmRuKI20zkrckYut4nebyW5hLk6EFkODh4d0IAZ6yms2oRkWGqE3eWlUQwBUrfu1SiAnw==", "article"=>{"title"=>"AYYE", "text"=>"Ma ka "}, "commit"=>"Create Article"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 13], ["LIMIT", 1]]
Completed 500 Internal Server Error in 6ms (ActiveRecord: 0.6ms)
NoMethodError (undefined method `user_id=' for nil:NilClass):
app/controllers/articles_controller.rb:26:in `create'
Here's the create method:
def create
#article.user_id = current_user.id
if #article.create
redirect_to #article
else
render 'new'
end
end
I am just starting out with RoR, hence unable to understand what's the problem here.
Apparently you #article is nil. It is throwing you error about calling/accessing user_id of nil object.
You need to make sure you define #article first, something like this
def create
#article = Article.new(article_params)
#article.user_id = current_user.id
if #article.save
redirect_to #article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
You have to create an instance of Article first. Then assign user_id and save the record.
def create
#article = Article.new
#article.user_id = current_user.id
#article.save
if #article.errors.any?
# error handling
else
render 'new'
end
end
I'm trying to install this app on Windows 7 https://github.com/cheezy/puppies.
I am not a developer, I am just following below steps to install it:
Ruby Version ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32] installed on Windows 7
Steps:
Download zip from above link
Inside puppies-master do bundle update and then bundle install.
Then rails s
Launch localhost:3000
It gave error ruby : unsupported parameters: :order. I fixed it by
changing this line
#puppies = Puppy.paginate :page =>params[:page], :order => 'name', :per_page => 4 to this line
#puppies = Puppy.order(:name).paginate(page: params[:page], per_page: 4)
Error was gone and on localhost:3000 it showed me the app launched
But puppies (data) weren't there so I did
bundle && rake db:create && rake db:migrate and then rake db:seed
Refresh the localhost page and all puppies appeared but after I am not able to complete the transaction and on hitting Complete the adoption button it is giving me an error.
undefined method 'name' for nil:NilClass
If you just type undefined method 'name' for nil:NilClass in SOF you will get so many solutions but it seems different then those, because none worked for me.
This is what log says:
Started GET "/orders/new" for 127.0.0.1 at 2017-07-20 10:10:51
Processing by OrdersController#new as HTML
Cart Load (0.0ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 1]]
Completed 500 Internal Server Error in 3ms
NoMethodError (undefined method `name' for nil:NilClass):
app/controllers/orders_controller.rb:23:in `new'
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.5ms)
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.0ms)
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (242.5ms)
Started GET "/orders/new" for 127.0.0.1 at 2017-07-20 11:20:21
Processing by OrdersController#new as HTML
Cart Load (0.0ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 1]]
Completed 500 Internal Server Error in 3ms
NoMethodError (undefined method `name' for nil:NilClass):
app/controllers/orders_controller.rb:23:in `new'
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (252.0ms)
Edit:
orders_controller.rb
class OrdersController < ApplicationController
skip_before_filter :authorize, :only => [:new, :create]
def index
#orders = Order.paginate :page=>params[:page], :order=>'created_at desc',
:per_page => 10
respond_to do |format|
format.html # index.html.erb
end
end
def show
#order = Order.find(params[:id])
respond_to do |format|
format.html # show.html.erb
end
end
def new
#cart = current_cart
if current_cart.adoptions.empty?
redirect_to agency_url, :notice => "Your cart is empty"
return
end
#order = Order.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #order }
end
end
def edit
#order = Order.find(params[:id])
end
def create
#order = Order.new(params[:order])
#order.add_adoptions_from_cart(current_cart)
respond_to do |format|
if #order.save
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
format.html { redirect_to(agency_url, :notice => 'Thank you for adopting a puppy!') }
format.json { render :json => #order }
else
format.html { render :action => "new" }
end
end
end
def update
#order = Order.find(params[:id])
respond_to do |format|
if #order.update_attributes(params[:order])
format.html { redirect_to(#order, :notice => 'Order was successfully updated.') }
else
format.html { render :action => "edit" }
end
end
end
def destroy
#order = Order.find(params[:id])
adoption = #order.adoptions.first
adoption.delivered_on = Time.now
adoption.save
respond_to do |format|
format.html { redirect_to(orders_url, :notice => "Please thank #{#order.name} for the order!") }
end
end
end
Edit2:
current_card method --
class ApplicationController < ActionController::Base
before_filter :authorize
protect_from_forgery
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
protected
def authorize
unless User.find_by_id(session[:user_id])
redirect_to login_url, :notice => "Please log in"
end
end
end
Here's my cart.rb model
class Cart < ActiveRecord::Base
has_many :tutors
def current_cart
if session[:cart_id]
#current_cart ||= Cart.find(session[:cart_id])
end
if session[:cart_id].nil?
#current_cart = Cart.create!
session[:cart_id] = #current_cart.id
end
#current_cart
end
def add_tutor(tutor_id)
tutor = Tutor.find(tutor_id)
if tutor
self.tutors << tutor
end
save
end
end
And here's my carts_controller.rb
class CartsController < ApplicationController
def show
#cart = current_cart
end
def checkout
#cart = current_cart
name = params[:checkout][:your_name]
email = params[:checkout][:your_email]
message = params[:checkout][:your_hp]
ApplicationMailer.checkout(#cart, name, email, message).deliver
flash[:success] = "We have received your request and will be in touch with you shortly!"
redirect_to root_path
end
def add_to_cart
#cart = current_cart.add_tutor(params[:tutor_id])
if #cart
flash[:success] = "You have successfully added the tutor to your cart!"
redirect_to tutors_path
else
flash[:danger] = "Oops! Something went wrong. Please try again!"
redirect_to root_path
end
end
end
And here's the button for the add to cart function
<%= button_to "Shortlist Tutor", add_to_cart_path(:tutor_id => tutor.id), :method => :post %>
The add to cart function seems to work fine as it redirects me to the correct page and no errors or anything like that seems to show up. In my rails console i can see in the server that there isn't any rollback.
Processing by CartsController#add_to_cart as HTML
Parameters: {"authenticity_token"=>"da3XDg69FSCrEyn39v8Apty4aX40TJH85BeW49x/4R3MElKYxip1w7rpbWRBYj5hhZDAivf7Bxn4FK1dkHyKpg==", "tutor_id"=>"3"}
Cart Load (0.2ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 12]]
Tutor Load (0.3ms) SELECT "tutors".* FROM "tutors" WHERE "tutors"."id" = ? LIMIT 1 [["id", 3]]
(0.1ms) begin transaction
(0.1ms) commit transaction
(0.1ms) begin transaction
(0.1ms) commit transaction
Thats what i see in the server. I'm really not quite sure why don't i see anything when i go to my carts#show view.
Would appreciate any help that i can get. Thanks!
Check what you are receiving in params[:tutor_id].
Looking at SQL statements that are executed it doesn't look like it is saving at all when invoking add_to_cart. It only carries out a SELECT on carts and tutor.
I'm working on an exercise, creating a blog with ruby on rails. I have the form ready to post an article, but once I click on the submit button, I am redirected to the homepage but the article doesn't save. Here is the following code
class ArticlesController < ApplicationController
def index
#articles = Article.paginate(:page => params[:page], per_page: 5).order('created_at DESC')
end
def show
#article = Article.find(params[:id])
end
def new
#article = Article.new
end
def create
#article = Article.new(title: params.permit[:title], body: params.permit[:body])
if #article.save
redirect_to articles, :notice => "Your post has been saved"
else
render :create
end
end
end
Here is the view create.html.haml
.container
.row
.col-xs-9-
.panel-title
%h2 Ecrivez votre article
= form_for #article do |f|
= f.text_field :title
= f.text_area :body, size: "60x12"
= f.submit "Publier"
Then the route.rb, I don't know if it can help
TP2::Application.routes.draw do
resources :articles, only: [:index]
get 'articles' => 'articles#index'
get 'articles/:id' => 'articles#show'
get 'articles/new'
get 'post' => 'articles#create'
post 'articles' => 'articles#index'
And to finish here is what the console show when I try to post an article
Started GET "/post" for 127.0.0.1 at 2016-04-10 14:24:56 +0200
Processing by ArticlesController#create as HTML
(0.2ms) BEGIN
(0.2ms) ROLLBACK
Rendered articles/create.html.haml within layouts/application (1.4ms)
Completed 200 OK in 9ms (Views: 4.9ms | ActiveRecord: 0.4ms)
Started POST "/articles" for 127.0.0.1 at 2016-04-10 14:25:10 +0200
Processing by ArticlesController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"FMQmKvZ1t98ZE21VaiBQhm0jKJ9x9BwkXFbh4obfi3Qea0Zax5dgGirfpgcAiQA464GMD2+Qv/eGYrmvEoTZBQ==", "article"=>{"title"=>"Post", "body"=>"New Article test"}, "commit"=>"Publier"}
Article Load (0.6ms) SELECT "articles".* FROM "articles" ORDER BY created_at DESC LIMIT 5 OFFSET 0
(0.4ms) SELECT COUNT(*) FROM "articles"
Rendered articles/index.html.haml within layouts/application (3.4ms)
Completed 200 OK in 7ms (Views: 5.3ms | ActiveRecord: 1.0ms)
I don't understand why the new article won't save. Does anyone understand why ?
I would simplify the routes:
Rails.application.routes.draw do
root to: 'articles#index' # or where you want for the first page
resources :articles #will give you the correct path and verbs
end
And the articles_controller.rb
class ArticlesController < ApplicationController
...
def create
#article = Article.new(article_params)
respond_to do |format|
if #article.save
format.html { redirect_to #article, notice: "Article created!" }
else
format.html { render action: 'new' }
end
end
end
private
def article_params
params.require(:article).permit(:title, :body)
end
end
Because you are learning new stuff, this is a way you should use to debug your code:
put a binding.pry (a breakpoint) on the line before #article.save (or use another debugger, you can find it on Github)
reload your page, input the fields and click Save
go to the rails console, issue #article.save on the console (or #article.valid?), it should return false
puts #article.errors, so you can what are the validation issues
Good luck :)